【问题标题】:Powershell notify when certificate almost expires当证书即将到期时,Powershell 会通知
【发布时间】:2021-12-08 20:29:01
【问题描述】:

在 Powershell 中,我想在域控制器中的证书提前 24 小时到期时通知特定用户。我已经找到了一个代码,然后显示开始和到期日期以及剩余天数。但是当证书过期时,我怎样才能得到通知(通过电子邮件)。

Get-ChildItem Cert:\LocalMachine\My `
   | Select @{N='StartDate';E={$_.NotBefore}},
   @{N='EndDate';E={$_.NotAfter}},
   @{N='DaysRemaining';E={($_.NotAfter - (Get-Date)).Days}} 

【问题讨论】:

  • 将该代码传递给Send-MailMessage?你试过什么吗?为什么它不起作用?
  • 我们还没有收到您的来信。我的回答解决了您的问题吗?如果是这样,请通过单击左侧的 图标来考虑accepting。这将帮助其他有类似问题的人更轻松地找到它,并有助于激励其他人回答您将来可能遇到的任何问题。

标签: powershell certificate


【解决方案1】:

我建议为您选择的对象添加更多属性以便稍后更好地识别,并为其添加Where-Object{} 子句,以过滤在到期前还有 1 天或更短时间的证书:

$certs = Get-ChildItem -Path 'Cert:\LocalMachine\My' |
   Select-Object Thumbprint, Issuer,
                 @{N='StartDate';E={$_.NotBefore}},
                 @{N='EndDate';E={$_.NotAfter}},
                 @{N='DaysRemaining';E={($_.NotAfter - (Get-Date).Date).Days}}  |
   Where-Object { $_.DaysRemaining -le 1 }

if ($certs) {
    # send an email to yourself
    $mailSplat = @{
        To         = 'me@mycompany.com'
        From       = 'me@mycompany.com'
        SmtpServer = 'MySmtpServer'
        Subject    = 'Expiring certificates'
        Body       = $certs | Format-List | Out-String
        # other params can go here
    }
    # send the email
    Send-MailMessage @mailSplat
}

(Get-Date).Date 将今天的日期设为午夜,而不是在您运行脚本的当前时间

【讨论】:

  • 你好,抱歉我有点忙。您的代码看起来不错,但是当我尝试发送邮件时出现错误:无法连接到远程服务器。我用 gmail 帐户尝试过,还添加了几个端口,如 25 和 587,但似乎没有工作..
  • @Ruan2106 这恐怕与您提出的问题无关。关于使用 gmail 发送电子邮件有 LOTS 的问题,至少您也可以在互联网上找到很多答案。最重要的是,您必须先更改 gmail 帐户中的一些设置,以使其“不太安全”才能使其正常工作。
猜你喜欢
  • 1970-01-01
  • 2011-07-13
  • 2020-08-12
  • 2021-08-25
  • 1970-01-01
  • 2021-04-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多