我想创建一个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
我创建了执行此任务的功能。
参数选项-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