foreach loop not working

Copper Contributor

$result = @()
$result += "KeyVaultCertName, KeyVaultName, KeyVaultCertExpiryDate"

$KEYVAULTS=$(az keyvault list --query "[].name")
foreach($KEYVAULT in $KEYVAULTS)
{
$AllKeyVaultCerts = $(az keyvault certificate list --vault-name "$KEYVAULT" --query "[].name")
foreach($KeyVaultCert in $AllKeyVaultCerts){
$KeyVaultName = $KeyVaultCert.VaultName
$KeyVaultCertName = $KeyVaultCert.Name
$KeyVaultCertEnabled = $KeyVaultCert.Enabled
$KeyVaultCertExpiryDate = $KeyVaultCert.expires
}
}

$KeyVaultName
$KeyVaultCertName
$KeyVaultCertExpiryDate
if($KeyVaultCertExpiryDate -lt ((Get-Date).AddDays(50))){
$result+="$KeyVaultCertName, $KeyVaultName, $KeyVaultCertEnabled, $KeyVaultCertExpiryDate"
$KeyVaultName
$KeyVaultCertName
$KeyVaultCertExpiryDate
}

 

 

the foreach loop is not working and hence I am not able to iterate through the KEYVAULTS

also, getting same output for KEYVAULT and KEYVAULTS

 

OUTPUT ERROR :-

ERROR: Max retries exceeded attempting to connect to Vault. The Vault may not exist or you may need to
flush your DNS cache and try again later.

1 Reply

@shresthasaluja 

 

You might find the Microsoft Azure Resource Manager module a little easier to use:

 

 

Here's the sample script that uses it.

 

$ExpiryThreshold = [datetime]::UtcNow.AddDays(50);

Get-AzKeyVault |
    ForEach-Object {
        $Vault = $_;

        Get-AzKeyVaultCertificate -VaultName ($Vault.VaultName) |
            Where-Object {
                $_.Expires -lt $ExpiryThreshold;
            } |
                ForEach-Object {
                    [PSCustomObject] @{
                        VaultName = $Vault.VaultName;
                        Name = $_.Name;
                        Enabled = $_.Enabled;
                        Expires = $_.Expires.ToString("u");
                    }
                }
    }

 

Which produces this output (I had to increase the expiry threshold given the dates were a year from now, but we're focusing on the formatting here, not the values):

 

LainRobertson_0-1665407041116.png

 

You can add Export-Csv to pipe that to a CSV file if you so desire.

 

I can't really speak to your error. It may be accurate or it may not - I cannot discern one way or another.

 

Cheers,

Lain