Powershell脚本在IIS中远程查找当前绑定的过期证书
问题描述:
我目前正在研究一个脚本,该脚本在绑定在我的Web服务器的IIS中的证书即将到期时发送一封电子邮件。我确实有脚本通过电子邮件发送。我只需要知道如何比较商店查询中可用的证书与当前正在使用的证书。现在,这是我有:Powershell脚本在IIS中远程查找当前绑定的过期证书
$Date= (Get-Date)
$SMTPServer = "smtp.test.com"
$From = "[email protected]"
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
任何帮助和建议,将不胜感激。谢谢!
答
上面的脚本永远不会工作,因为您正在将不同会话中的变量创建到同一台计算机。
你可以用两种方法做到这一点。
创建一个以目标服务器为目标的会话对象,并重新使用它。这样你就可以在随后的
Invoke-command
执行中获得会话中定义的变量。不创建会话对象,而是通过在单个
Invoke-Command
中执行远程服务器上的所有操作。
例如: -
Invoke-command -computerName $Server {
$CertAll = ....
$CertInUse = ....
$CertSame = ....
$cert = $CertSame | ForEach ..... |
Select-Object Subject, DaysUntilExpired .....
}
,如果您还没有确定certiricates后的远程服务器上的任何进一步行动到期日期,我会建议使用第二个选项。
答
@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天过期并发送电子邮件通知的证书时发送电子邮件。我会在另一篇帖子中提出我的担忧。
我必须为每台服务器创建一个'Invoke-Command'吗? – Didge
@Didge新增示例 –
我现在明白了。对不起,先生。但我想我不能访问'IIS:\ SslBindings'。我总是得到错误,说'找不到驱动器。名称'IIS'的驱动器不存在.' 这是我认为的部分,我得到了以下错误: 'Get-ChildItem -Path IIS:\ SslBindings' – Didge