A.Bux
A.Bux

Reputation: 109

Powershell script won't list expired key vault certificates

I have a powershell script that is attempting to list all the expired secrets of my Azure Key Vault. Unfortunately I'm struggling to do this.

This is how I retrieve sercrets. But what do I need to add to get the expiration of all secrets? Then delete those that are expired? I'm guessing I'll need to set an access policy.

Select-AzSubscription -Subscription "My subscriptsion"
Set-AzKeyVaultAccessPolicy -VaultName "testKeyVaultPwsh" -UserPrincipalName "[email protected]" -PermissionsToSecrets get,set,delete

#Retrieve secret
$secret = Get-AzKeyVaultSecret -VaultName "testKeyVaultPwsh" -Name "ExamplePassword" -AsPlainText

Upvotes: 0

Views: 1049

Answers (1)

kavya Saraboju
kavya Saraboju

Reputation: 10831

  • You can delete the expired secrets using below commands .(Make sure you have get,set,delete access policies set and given proper permissions )

I have tried in my environment and able to delete expired secrets sussessfully.

After checking expiry using

$exp =Get-AzKeyVaultSecret -VaultName $vaultname -Name $secretname | Select-Object Name,Expires
$exp
  • I created secrets and have secrets expired.

enter image description here

Commands:

$vaultname= “<keyvaultname>”
$secrets= Get-AzKeyVaultSecret -VaultName $vaultname
$secretnames =$secrets.Name
$current_date=Get-Date
Foreach($secretname in $secretnames)
{
$exp =Get-AzKeyVaultSecret -VaultName $vaultname -Name $secretname | Select-Object Expires
$keyvaultsecretvexpirydate =[datetime]($exp.Expires)

             $timediff=NEW-TIMESPAN -Start $current_date -End $keyvaultsecretvexpirydate
             $days_until_expiration=$timediff.Days
Write-Output “days_until_expiration  of secret named $secretname is  :$days_until_expiration”
Write-Output “ ”

if ($days_until_expiration -eq 0) 
{
    Write-Output  "Secret named $secretname got expired “
Write-Output  “removing expired secret : $secretname”
Write-Output  “ ”
Remove-AzKeyVaultSecret -VaultName $vaultname -Name $secretname
}

}

enter image description here

Confirm to delete by typing Y and refresh the secrets page to see the expired secret being removed/deleted.

enter image description here

References:

  1. KeyVaultSecretExpirationAlerts |github
  2. remove-azkeyvaultsecret | microsoftdocs

Upvotes: 1

Related Questions