我想创建一个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
答案 0 :(得分:0)
我创建了一个函数来执行此任务。
参数选项为-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