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

时间:2017-10-18 20:52:04

标签: powershell powershell-remoting windows-scripting

我目前正在制作一个脚本,一旦我的网络服务器的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

任何帮助和建议将不胜感激。谢谢!

2 个答案:

答案 0 :(得分:0)

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

你可以用两种方式做到这一点。

  1. 创建一个针对目标服务器的会话对象并重复使用它。这样您就可以在后续的Invoke-command执行中获得会话中定义的变量。

  2. 不创建会话对象,而是通过单个Invoke-Command执行远程服务器上的所有内容。

  3. 例如: -

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

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

答案 1 :(得分:0)

@PRASOON我已经设法远程检查我的证书。我尝试使用谷歌中发现的不同参考文献。无论如何,这是剧本。

$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天后过期并发送电子邮件通知时发送电子邮件。我将在另一篇文章中提出我的担忧。