远程查找 IIS 中当前绑定的过期证书的 Powershell 脚本

Powershell script to find currently bound expiring certificates in IIS remotely

我目前正在编写一个脚本,一旦我的 Web 服务器的 IIS 中绑定的证书接近到期日期,该脚本就会发送一封电子邮件。我确实有通过电子邮件发送的脚本。我只需要知道如何将商店查询中可用的证书与当前使用的证书进行比较。现在,这是我所拥有的:

$Date= (Get-Date)
$SMTPServer = "smtp.test.com" 
$From = "testmail@noreply.com"

Import-Module WebAdministration

$Servers = @("WEBSERVER1", "WEBSERVER2")

$certificates = foreach($server in $Servers){
    Invoke-Command -ComputerName $server -ScriptBlock { $CertAll = Get-ChildItem -Path Cert:\LocalMachine\My }
    Invoke-Command -ComputerName $server -ScriptBlock { $CertInUse = Get-ChildItem -Path IIS:\SslBindings }
    Invoke-Command -ComputerName $server -ScriptBlock { $CertSame = Compare-Object -ReferenceObject $CertAll -DifferenceObject $CertInUse -Property Thumbprint -IncludeEqual -ExcludeDifferent }

    Invoke-Command -ComputerName $server -ScriptBlock { $cert = $CertSame | ForEach {Get-ChildItem -Path Cert:\LocalMachine\My$($_.thumbprint)} | 
  Select-Object Subject, DaysUntilExpired, NotAfter, @{n='ExpireInDays';e={($_.notafter - ($Date)).Days}}}
}

    $certificates | Sort DisplayName

如有任何帮助和建议,我们将不胜感激。谢谢!

上面的脚本永远不会工作,因为您在同一台计算机的不同会话中创建变量。

您可以通过两种方式完成。

  1. 创建一次以目标服务器为目标的会话对象并重新使用它。这样你就可以在后续的Invoke-command次执行中得到session中定义的变量。

  2. 不创建会话对象,而是通过在单个 Invoke-Command .

  3. 中执行远程服务器上的所有内容

示例:-

Invoke-command -computerName $Server {
    $CertAll = ....
    $CertInUse = ....
    $CertSame = ....
    $cert = $CertSame | ForEach ..... |
    Select-Object Subject, DaysUntilExpired .....

}

如果您在确定证书到期日期后在远程服务器上没有任何进一步的操作,我建议使用第二个选项。

@PRASOON 我已经设法远程检查了我的证书。我尝试使用在 google 中找到的不同参考文献。无论如何,这是脚本。

$Date = Get-Date
$servers = Get-Content C:\servers.txt

$cert = Foreach ($server in $servers) {
    Invoke-Command -ComputerName $server -ScriptBlock{
        Import-Module WebAdministration; Get-ChildItem -Path IIS:SslBindings | ForEach-Object -Process{
            if ($_.Sites)
                {
                    $certificate = Get-ChildItem -Path CERT:LocalMachine\My |
                        Where-Object -Property Thumbprint -EQ -Value $_.Thumbprint

                    [PSCustomObject]@{
                        Sites = $_.Sites.Value
                        DnsNameList = $certificate.DnsNameList
                        NotAfter = $certificate.NotAfter
                        ExpireInDays = ($certificate.NotAfter - (Get-Date)).Days}
                }
            } 
        }
    } 

$cert | Select PSComputerName, DnsNameList, NotAfter, ExpireInDays | Where-Object {$_.ExpireInDays -lt 30} | Out-File C:\results.txt

所以基本上,这将显示将恰好或从现在起 30 天内到期的证书。我仍在努力解决这个问题,因为我要做的是在脚本检测到证书将从当前日期起 30 天后过期并发送电子邮件通知时发送电子邮件。我会在另一个 post.

中询问我的担忧