需要为 PowerShell Runbook 设置电子邮件通知,以定期/每天将其输出发送到邮件

问题描述 投票:0回答:1

我正在尝试将密钥保管库中已过期且将在 7 天后过期的所有机密和密钥的列表发送至我的邮件。

我已经创建了自动化帐户并使用 PowerShell 脚本发布了 Runbook,该脚本为我的上述查询提供了输出

请帮助我了解如何每天或定期从 Runbook 接收 PowerShell 脚本输出到我的邮件?

$expirationDetails = @()

# Get all subscriptions
$subscriptions = Get-AzSubscription

# Loop through each subscription
foreach ($subscription in $subscriptions) {
    # Set the context to the current subscription
    Set-AzContext -SubscriptionId $subscription.Id

    # Get all Key Vaults in the current subscription
    $kvnames = Get-AzKeyVault

    foreach ($kvitem in $kvnames) {
        # Get Key Vault secrets, keys, and certificates
        $secrets = Get-AzKeyVaultSecret -VaultName $kvitem.VaultName
        $keys = Get-AzKeyVaultKey -VaultName $kvitem.VaultName
        $certificates = Get-AzKeyVaultCertificate -VaultName $kvitem.VaultName

        # Function to check expiration date and return the expiration DateTime or null for missing values
        function Check-Expiration($expiryDate) {
            if ($expiryDate) {
                return [datetime]$expiryDate  # Return the DateTime object if expiration date exists
            }
            return $null  # Return null if expiration date is missing
        }

        # Function to calculate remaining days
        function Get-RemainingDays($expiryDate) {
            if ($expiryDate -ne $null) {
                $remainingDays = ($expiryDate - (Get-Date)).Days
                return $remainingDays
            }
            return $null  # Return null if no expiration date
        }

        # Process secrets
        foreach ($secret in $secrets) {
            $expirationDate = Check-Expiration $secret.Expires
            $remainingDays = Get-RemainingDays $expirationDate

            if ($expirationDate -ne $null) {
                $formattedExpirationDate = $expirationDate.ToString("MM/dd/yyyy HH:mm:ss")
            } else {
                $formattedExpirationDate = ""  # Empty string for null expiration dates
            }

            # Only include items expiring within the next 7 days
            if ($remainingDays -le 7 -and $remainingDays -ge 0) {
                $expirationDetails += [PSCustomObject]@{
                    SubscriptionName  = $subscription.Name
                    ResourceGroupName = $kvitem.ResourceGroupName
                    ResourceName      = $kvitem.VaultName  # Key Vault name
                    ObjectName        = $secret.Name        # Name of the secret
                    ObjectCategory    = "Secret"            # Category for KeyVault secret
                    ExpirationDate    = $formattedExpirationDate  # Formatted expiration date
                    ExpiresIn         = $remainingDays     # Remaining days until expiration
                }
            }
        }

        # Process keys
        foreach ($key in $keys) {
            $expirationDate = Check-Expiration $key.Attributes.Expires
            $remainingDays = Get-RemainingDays $expirationDate

            if ($expirationDate -ne $null) {
                $formattedExpirationDate = $expirationDate.ToString("MM/dd/yyyy HH:mm:ss")
            } else {
                $formattedExpirationDate = ""  # Empty string for null expiration dates
            }

            # Only include items expiring within the next 7 days
            if ($remainingDays -le 7 -and $remainingDays -ge 0) {
                $expirationDetails += [PSCustomObject]@{
                    SubscriptionName  = $subscription.Name
                    ResourceGroupName = $kvitem.ResourceGroupName
                    ResourceName      = $kvitem.VaultName  # Key Vault name
                    ObjectName        = $key.Name           # Name of the key
                    ObjectCategory    = "Key"               # Category for KeyVault key
                    ExpirationDate    = $formattedExpirationDate  # Formatted expiration date
                    ExpiresIn         = $remainingDays     # Remaining days until expiration
                }
            }
        }

        # Process certificates
        foreach ($certificate in $certificates) {
            $expirationDate = Check-Expiration $certificate.Attributes.Expires
            $remainingDays = Get-RemainingDays $expirationDate

            if ($expirationDate -ne $null) {
                $formattedExpirationDate = $expirationDate.ToString("MM/dd/yyyy HH:mm:ss")
            } else {
                $formattedExpirationDate = ""  # Empty string for null expiration dates
            }

            # Only include items expiring within the next 7 days
            if ($remainingDays -le 7 -and $remainingDays -ge 0) {
                $expirationDetails += [PSCustomObject]@{
                    SubscriptionName  = $subscription.Name
                    ResourceGroupName = $kvitem.ResourceGroupName
                    ResourceName      = $kvitem.VaultName  # Key Vault name
                    ObjectName        = $certificate.Name  # Name of the certificate
                    ObjectCategory    = "Certificate"       # Category for KeyVault certificate
                    ExpirationDate    = $formattedExpirationDate  # Formatted expiration date
                    ExpiresIn         = $remainingDays     # Remaining days until expiratio
                }
            }
        }
    }
}

# Optionally, display the results on the screen
$expirationDetails | Format-Table -Property SubscriptionName, ResourceGroupName, ResourceName, ObjectName, ObjectC
azure azure-powershell azure-keyvault azure-automation azure-runbook
1个回答
0
投票

要从 Azure 自动化 Runbook 发送电子邮件,我找到了一种使用名为

Send-MailMessage
的 PowerShell 命令的方法。但正如我在评论中提到的,该命令
Send-MailMessage
已过时,此 cmdlet 不能保证与 SMTP 服务器的安全连接。

我尝试将其与 PowerShell 脚本一起执行,并且警告以以下格式出现。

While there is no immediate replacement available in PowerShell, we recommend you do not use Send-MailMessage at this time.

相关问题请参阅此Microsoft Q&A

作为一种解决方法,我尝试了下面的 PowerShell 脚本,编写一个查询来检索已过期的机密列表并建立了 smtp 服务器连接。

$query = @"
resources
| where type == "microsoft.keyvault/vaults"
| extend vaultUri = properties.vaultUri
| join kind=inner (
    resources
    | where type == "microsoft.keyvault/vaults/secrets"
    | extend vaultName = tostring(split(id, "/")[8]), resourceName = name
    | extend expired = properties.attributes.expiresOn
    | project vaultName,expired
) on $left.vaultName == $right.vaultName
| where expired < ago(1d)
| project vaultUri
"@
$result = Search-AzGraph -Query $query

$pwd = ConvertTo-SecureString '*****' -AsPlainText -Force
$CredSmtp = New-Object System.Management.Automation.PSCredential ('jahxxx@gmail', $password)$pwd = ConvertTo-SecureString 'Jahnavim@2727' -AsPlainText -Force
$CredSmtp = New-Object System.Management.Automation.PSCredential ('jxxxx@gmail', $pwd)
$FromMail = "jaxxxxgmail.com"
$MailTo = "xxxxx.com"
$Username = $CredSmtp.UserName
$Password = $CredSmtp.Password
$SmtpServer = "smtp.gmail.com"
$Port = 587
$Message = New-Object System.Net.Mail.MailMessage $FromMail, $MailTo
$MessageSubject = "Sending Automation results"
$Message.IsBodyHTML = $true
$Message.Subject = $MessageSubject
$Smtp = New-Object Net.Mail.SmtpClient($SmtpServer, $Port)
$Smtp.EnableSsl = $true
$Smtp.Credentials = New-Object System.Net.NetworkCredential($Username, $Password)
$Smtp.Send($Message)

消息格式如下:

enter image description here

参考@Sridevi 的SO,了解发送电子邮件的相关信息。

或者,您还可以通过在 Azure Monitor 工作区中添加上述 KQL 查询,使用 Azure 监控中提供的警报规则每天或定期创建和触发警报。

详细信息参见 MSDoc

© www.soinside.com 2019 - 2024. All rights reserved.