Might find the following useful ...
You need the vaultUri property for JMESPath contains() later so ...
($resource = az resource show --subscription ($subscription = 'MY_SUBSCRIPTION') --resource-group ($resourceGroup = 'MY_RESOURCE_GROUP') --resource-type 'Microsoft.KeyVault/vaults' --name ($resourceName = 'MY_KEYVAULT_NAME') --output json | ConvertFrom-Json) | Format-List
Use az keyvault key list --query
to return whether NAME_OF_KEY exists or not - as suggested by roozbeh
(az keyvault key list --subscription $subscription --vault-name $resourceName --query ("contains([].kid, '{0}keys/{1}')" -F $resource.Properties.vaultUri, ($keyName = "NAME_OF_KEY")))
and if MY_KEY_NAME exists then the following will return the enabled revisions in reversed createdBy order, i.e. latest revision as [0]
($listVersions = az keyvault key list-versions --subscription $subscription --vault-name $resourceName --name $keyName --query "reverse(sort_by([?attributes.enabled], &attributes.created))" --output json | ConvertFrom-Json) | Format-List
I couldn't get the datetime for NotBefore & Expires to work within JMESPath so the PowerShell equivalent is ...
($activeVersions = $listVersions | Where-Object { (($null -eq $_.attributes.notbefore) -or ($_.attributes.notbefore -le ($Now = [System.DateTime]::Now))) -and (($null -eq $_.attributes.expires) -or ($_.attributes.expires -gt $Now)) }) | Format-List
and then show details of the latest active version of MY_KEY_NAME using
($key = az keyvault key show --subscription $subscription --vault-name $resourceName --name $keyName --version ($activeVerions[0].kid -replace ('^.+/', '')) --output json | ConvertFrom-Json) | Format-List
although the latest version needs to be enabled for usage so the following is just fine:
($key = az keyvault key show --subscription $subscription --vault-name $resourceName --name $keyName --output json | ConvertFrom-Json) | Format-List