我有一个简单的脚本来显示服务器上的所有证书,我想扩展该脚本以删除所有过期的证书
我尝试了来自 MS 和第 3 方的多个脚本来查找删除证书,但没有让它们正常工作
我使用的第一个代码是:
获取子项证书:\ -Recurse
此 Powershell 脚本显示服务器上的所有证书。
每个证书的输出示例如下。我想定位 NotAfter 字段并让脚本删除证书(如果证书早于今天的日期)
主题: 发行人: 指纹: 友好名称: 之前没有: 不之后: 扩展
我还想对服务器列表执行此操作,让脚本在文本文档中的每个服务器上运行,查询所有证书,然后删除过期的证书并移至下一个服务器。
我看到了一些针对日期的代码,如下所示:
ForEach-Object -begin { $now = get-date } -process { if ($PSItem.NotAfter -lt $now ) { $PSItem } } |删除项目
我希望脚本出去查询服务器证书,然后删除过期的证书
你所追求的就是这个。这应该非常适合你。你的逻辑很接近,只是执行起来似乎有点不对劲。
$ListOfServers = Get-Content "c:\temp\serv.txt"
Foreach($Server in $ListOfServers) {
Invoke-Command -ComputerName $Server -ScriptBlock {
# Get Certificate list and assign to a variable
$Certs = Get-ChildItem "Cert:\LocalMachine\My" -Recurse
# Loop through each object in $Certs
Foreach($Cert in $Certs) {
# If The objects property "NotAfter" is older than the current time, delete
If($Cert.NotAfter -lt (Get-Date)) {
$Cert | Remove-Item
}
}
}
}
根据评论进行编辑,以防止意外破坏所有证书。
获取所有证书存储位置的列表。
(Get-ChildItem -Path "Cert:" -Recurse `
| Where-Object {($_).GetType().Name -eq 'X509Store'}).Name
功能删除过期的个人证书{ 获取子项证书:\CurrentUser\My | ForEach-Object {if ($.NotAfter -lt (Get-Date)) {Remove-Item -LiteralPath $.pspath }} }