使用 Powershell 删除过期证书

azt*_*ech 4 powershell certificate client-certificates ssl-certificate x509certificate

我有一个简单的脚本来显示服务器上的所有证书,我想扩展该脚本以删除所有过期的证书

我已经尝试了来自 MS 和 3rd 方的几个脚本来查找删除证书,但它们无法正常工作

我使用的第一个代码是:

Get-ChildItem Cert:\ -Recurse

此 Powershell 脚本显示服务器上的所有证书。

每个证书的示例输出如下。我想定位 NotAfter 字段并使用脚本然后删除证书,如果它比今天的日期旧

主题:发行人:指纹:友好名称:NotBefore:NotAfter:扩展

我还想为服务器列表执行此操作,在文本文档中的每个服务器上运行脚本,查询所有证书,然后删除过期的证书并移至下一个服务器。

我见过一些针对日期的代码,如下所示:

ForEach-Object -begin { $now = get-date } -process { if ($PSItem.NotAfter -lt $now ) { $PSItem } } | 除去项目

我希望脚本出去查询服务器证书,然后删除过期的证书

Dre*_*rew 6

你所追求的是这个。这应该非常适合您。你的逻辑很接近,只是执行似乎有点偏离。

$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
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

根据评论进行编辑,以防止意外破坏所有证书。

获取所有证书存储位置的列表。

(Get-ChildItem -Path "Cert:" -Recurse `
    | Where-Object {($_).GetType().Name -eq 'X509Store'}).Name
Run Code Online (Sandbox Code Playgroud)