PowerShell Output Property Formatting

69 Views Asked by At

I'm relatively new to PowerShell and have been trying to pull a list of all the Key Vaults in our Azure subscription with specific properties. One of these properties is Purge Protection Enabled, which I've managed to select in the code below:

$kvs = Get-AzKeyVault

foreach ($kv in $kvs) {

    $resourceDetail = [PSCustomObject]@{
        KVName                = $kv.VaultName
        ResourceGroup         = $kv.ResourceGroupName
        PurgeProtection       = Get-AzKeyVault -VaultName $kv.VaultName | Select-Object -Property EnablePurgeProtection
    }

    $resourceDetail
}

However the output is provided in this format @{EnablePurgeProtection=True}

Is there a better way of selecting the property or formatting it so that it just shows "True" or "False?

Thanks

1

There are 1 best solutions below

1
Santiago Squarzon On

Your code can be summarized to:

Get-AzKeyVault | Select-Object VaultName, ResourceGroupName, EnablePurgeProtection

There is no need to re-query each key vault, you're already doing that on your first Get-AzKeyVault call.

If you want custom names for your properties you can use calculated properties, though code becomes less readable.

Get-AzKeyVault | Select-Object @(
    @{ N = 'KVName'; E = 'VaultName' }
    @{ N = 'ResourceGroup'; E = 'ResourceGroupName' }
    @{ N = 'PurgeProtection'; E = { $_.EnablePurgeProtection -as [bool] }})

Another way to do it using Search-AzGraph:

Search-AzGraph "
resources
| where ['type'] =~ 'microsoft.keyvault/vaults'
| extend EnablePurgeProtection = iif(
    tobool(properties.enablePurgeProtection), 'true', 'false')
| project
    KVName = name,
    ResourceGroup = resourceGroup,
    EnablePurgeProtection
"