Powershell脚本删除过期的证书 [英] Powershell Script to remove expired certificates

查看:134
本文介绍了Powershell脚本删除过期的证书的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个Powershell脚本,该脚本将删除过期的证书,但是我一直收到错误消息。

I want to create a powershell script that will remove expired certificates but I keep receiving an error.

我还更改了notafter属性以显示为到期日期。

I also changed the notafter property to display as expiration date.


        $today = Get-Date
        dir Cert:\LocalMachine\My\|
        select  thumbprint, subject, @{Name="ExpirationDate";Expression= 
        {$_.NotAfter}}|
        Where-Object ExpirationDate -lt $today|
        Remove-Item




Remove-Item : Cannot find drive. A drive with the name '@{Thumbprint=XXXX; 
Subject=CN=xyz.org, OU=X, O=X, L=X, S=X, 
C=US; NotAfter=X' does not exist.
At C:\Users\Documents\Delete Expired Certs Script.ps1:10 char:2
+  Remove-Item 
+  ~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (@{Thumbprint=70...r=:String) [Remove-Item], DriveNotFoun 
   dException
    + FullyQualifiedErrorId : DriveNotFound,Microsoft.PowerShell.Commands.RemoveItemCommand


推荐答案

I'

参数选项为 -CertificateStore LocalMachine -CertificateStore CurrentUser

可选的 -WhatIf 参数将指出要删除的证书。

Optional -WhatIf parameter will state which certificates will be removed.

可选的 -Verbose 参数将说明证书DN及其有效期。

Optional -Verbose parameter will state the certificate DN and its expiry date.

function Remove-ExpiredCertificates {
    [CmdletBinding(SupportsShouldProcess)]
    param(
        [Parameter(Mandatory)]
        [ValidateSet('LocalMachine','CurrentUser')]
        [string]$CertificateStore
    )
    process{
        $today = Get-Date
        $path = "Cert:\$CertificateStore\My"
        $expiredCertList = Get-ChildItem -Path $path | Where-Object -Property NotAfter -lt $today

        foreach ($certificate in $expiredCertList){
            if ($PSCmdlet.ShouldProcess("certificate $($certificate.Subject) that expired $($certificate.NotAfter)",'Remove')){
                Remove-Item -Path $certificate.PSPath -Force
            }
        }
    }
}

示例输出:

PS > Remove-ExpiredCertificates -CertificateStore LocalMachine -WhatIf
What if: Performing the operation "Remove" on target "certificate CN=myoldcert.domain.local that expired 01/31/2018 11:59:00"

PS > Remove-ExpiredCertificates -CertificateStore LocalMachine

这篇关于Powershell脚本删除过期的证书的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆