【问题标题】:Powershell Script to remove expired certificates用于删除过期证书的 Powershell 脚本
【发布时间】:2019-06-24 02:06:36
【问题描述】:

我想创建一个用于删除过期证书的 powershell 脚本,但我一直收到错误消息。

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


        $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

【问题讨论】:

  • 我猜你有 PowerShell 2.0。你至少需要 3.0 才能工作。
  • 省略/删除 select 部分。管道应该如下:dir Cert:\LocalMachine\My\| Where-Object NotAfter -lt $today | Remove-Item
  • @Matt 我很确定 ps v2 上也存在证书驱动器。问题是他们试图使用Remove-Item 对抗他们用Select-Object 制作的pscustomobject。他们的 Where-Object 语法表明他们在 PSv3+ 上。投票结束问题作为题外话:语法错误。
  • @TheIncorrigible1 它不是驱动器。它是Remove-Item 和 2.0 中存在的提供程序的问题。但是......我没有注意到管道中的对象发生了变化,这很可能是第一个罪魁祸首。

标签: powershell certificate


【解决方案1】:

我已经创建了一个函数来执行这个任务。

参数选项为-CertificateStore LocalMachine-CertificateStore CurrentUser

可选的-WhatIf 参数将说明将删除哪些证书。

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

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

【讨论】:

    猜你喜欢
    • 2019-10-02
    • 2023-03-24
    • 2013-04-17
    • 2022-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-24
    相关资源
    最近更新 更多