简体   繁体   中英

Simplify PowerShell runbook to send e-mail

Can I simplify my PowerShell Azure runbook to gather soon to expire secrets and certs (vs repeating code) from all KV's in subscription and send a formatted table in an e-mail?

The current runbook runs fine with the associated modules configured to the automation account in the subscription but I'm positive there is a much cleaner way to run this and have a formatted email go out to stakeholders periodically.

Param(
        [string]$SubscriptionID = "",
        [int]$DaysNearExpiration = "30",
        [string]$VaultName
)
 
Get-AzureRmSubscription -SubscriptionId $SubscriptionID | Select-AzureRmSubscription | Format-Table -Autosize
 
$ExpiredSecrets = @()
$NearExpirationSecrets = @()

#gather all key vaults from subscription
if ($VaultName) {
    $KeyVaults = Get-AzureRmKeyVault -VaultName $VaultName
}
else {
    $KeyVaults = Get-AzureRmKeyVault
}
#check date which will notify about expiration
$ExpirationDate = (Get-Date (Get-Date).AddDays($DaysNearExpiration) -Format yyyyMMdd)
$CurrentDate = (Get-Date -Format yyyyMMdd)
 
# iterate across all key vaults in subscription
foreach ($KeyVault in $KeyVaults) {
    # gather all secrets in each key vault
    $SecretsArray = Get-AzureKeyVaultSecret -VaultName $KeyVault.VaultName
    foreach ($secret in $SecretsArray) {
        # check if expiration date is set
        if ($secret.Expires) {
            $secretExpiration = Get-date $secret.Expires -Format yyyyMMdd
            # check if expiration date set on secret is before notify expiration date
            if ($ExpirationDate -gt $secretExpiration) {
                # check if secret did not expire yet but will expire soon
                if ($CurrentDate -lt $secretExpiration) {
                    $NearExpirationSecrets += New-Object PSObject -Property @{
                        Name           = $secret.Name;
                        Category       = 'SecretNearExpiration';
                        KeyVaultName   = $KeyVault.VaultName;
                        ExpirationDate = $secret.Expires;
                    }
                }
                # secret is already expired
                else {
                    $ExpiredSecrets += New-Object PSObject -Property @{
                        Name           = $secret.Name;
                        Category       = 'SecretNearExpiration';
                        KeyVaultName   = $KeyVault.VaultName;
                        ExpirationDate = $secret.Expires;
                    }
                }
 
            }
        }
    }
         
}
 
Write-Output "Total number of expired secrets: $($ExpiredSecrets.Count)"
$ExpiredSecrets
  
Write-Output "Total number of secrets near expiration: $($NearExpirationSecrets.Count)"
$NearExpirationSecrets

$ExpiredCertificates = @()
$NearExpirationCertificates = @()

#gather all key vaults from subscription
if ($VaultName) {
    $KeyVaults = Get-AzureRmKeyVault -VaultName $VaultName
}
else {
    $KeyVaults = Get-AzureRmKeyVault
}
#check date which will notify about expiration
$ExpirationDate = (Get-Date (Get-Date).AddDays($DaysNearExpiration) -Format yyyyMMdd)
$CurrentDate = (Get-Date -Format yyyyMMdd)
 
# iterate across all key vaults in subscription
foreach ($KeyVault in $KeyVaults) {
    # gather all certificates in each key vault
    $CertificatesArray = Get-AzureKeyVaultCertificate -VaultName $KeyVault.VaultName
    foreach ($Certificate in $CertificatesArray) {
        # check if expiration date is set
        if ($certificate.Expires) {
            $certificateExpiration = Get-date $certificate.Expires -Format yyyyMMdd
            # check if expiration date set on certificate is before notify expiration date
            if ($ExpirationDate -gt $certificateExpiration) {
                # check if secret did not expire yet but will expire soon
                if ($CurrentDate -lt $certificateExpiration) {
                    $NearExpirationCertificates += New-Object PSObject -Property @{
                        Name           = $certificate.Name;
                        Category       = 'CertificateNearExpiration';
                        KeyVaultName   = $KeyVault.VaultName;
                        ExpirationDate = $certificate.Expires;
                    }
                }
                # secret is already expired
                else {
                    $ExpiredCertificates += New-Object PSObject -Property @{
                        Name           = $certificate.Name;
                        Category       = 'CertificateNearExpiration';
                        KeyVaultName   = $KeyVault.VaultName;
                        ExpirationDate = $certificate.Expires;
                    }
                }
 
            }
        }
    }
         
}
 
Write-Output "Total number of expired certificates: $($ExpiredCertificates.Count)"
$ExpiredCertificates
  
Write-Output "Total number of certificates near expiration: $($NearExpirationCertificates.Count)"
$NearExpirationCertificates

Here is a possible refactoring (untested):

Param(
        [string]$SubscriptionID = "",
        [int]$DaysNearExpiration = "30",
        [string]$VaultName
)
 
Get-AzureRmSubscription -SubscriptionId $SubscriptionID | Select-AzureRmSubscription | Format-Table -Autosize

$ExpiredSecrets = [System.Collections.Generic.List[PSCustomObject]] @()
$NearExpirationSecrets = [System.Collections.Generic.List[PSCustomObject]] @()

#gather all key vaults from subscription
$KeyVaultArgs = if( $VaultName ) { @{ VaultName = $VaultName } } else { @{} } 
# In PS 7+ you could write:
# $KeyVaultArgs = $VaultName ? @{ VaultName = $VaultName } : @{} 
$KeyVaults = Get-AzureRmKeyVault @KeyVaultArgs

#check date which will notify about expiration
$ExpirationDate = (Get-Date (Get-Date).AddDays($DaysNearExpiration) -Format yyyyMMdd)
$CurrentDate = (Get-Date -Format yyyyMMdd)
 
# iterate across all key vaults in subscription
foreach ($KeyVault in $KeyVaults) {
    # gather all secrets in each key vault
    $SecretsArray = Get-AzureKeyVaultSecret -VaultName $KeyVault.VaultName | Where-Object Expires

    foreach ($secret in $SecretsArray) {
        # check if expiration date is set
        $secretExpiration = Get-date $secret.Expires -Format yyyyMMdd
        # check if expiration date set on secret is before notify expiration date
        if ($ExpirationDate -gt $secretExpiration) {
            $secret = [PSCustomObject]@{
                Name           = $secret.Name
                Category       = 'SecretNearExpiration'
                KeyVaultName   = $KeyVault.VaultName
                ExpirationDate = $secret.Expires
            }

            # check if secret did not expire yet but will expire soon
            if ($CurrentDate -lt $secretExpiration) {
                $NearExpirationSecrets.Add( $secret )
            }
            # secret is already expired
            else {
                $ExpiredSecrets.Add( $secret )
            }
        }
    }       
}

# omitted unmodified code ...

Changes:

  • Use [System.Collections.Generic.List[PSCustomObject]] instead of plain array. This is much more efficient when the array can grow large. Powershell recreates a plain array to size +1 whenever operator += is used. A list 's internal array will be resized only in multiples of two instead.
  • $KeyVaultArgs = if... uses conditional assignment to create the parameters as a hashtable and then uses splatting to need only a single call to Get-AzureRmKeyVault .
  • $SecretsArray = Get-AzureKeyVaultSecret -VaultName $KeyVault.VaultName | Where-Object Expires $SecretsArray = Get-AzureKeyVaultSecret -VaultName $KeyVault.VaultName | Where-Object Expires lets us get rid of the if ($secret.Expires) within the foreach , reducing nesting level.
  • $secret = [PSCustomObject]@{ to remove duplicate code from the if/else construct below. Also slightly cleaner syntax than New-Object PSObject .
  • $NearExpirationSecrets.Add( $secret ) and $ExpiredSecrets.Add( $secret ) are required because list doesn't support the += operator.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM