获取在一个月或更短时间内过期的证书

Get certificates to expire in one month or less

我想获取最多一个月后到期的所有本地机器证书,并将它们的信息存储在一个.csv文件中。我使用了这段代码,但它还存储了一些其他将在一个多月后过期的证书。

这是我写的代码:

$testPath = 'Cert:\LocalMachine\'
$testDetail = Get-ChildItem -Path $testPath -Recurse | Where-Object {
    $_.PSIsContainer -ne $true
} | ForEach-Object {
    $DaysLeft = (New-TimeSpan -Start $StartDate -End $_.NotAfter).Days

    $FinalDate = Get-Date $_.NotAfter -Format 'dd/MM/yyyy hh:mm'
    $Usages = ($_.Extensions | Where-Object {$_.KeyUsages}).KeyUsages
    if ($Usages) {
        # get at most two parts out of the $_.Issuer string
        $issuer = '{0}, {1}' -f ([regex] 'O=([^,]+)').Match($_.Issuer).Groups[1].Value, 
                                ([regex] 'CN=([^,]+)').Match($_.Issuer).Groups[1].Value
        $issuer = $issuer.Trim(", ")

        [PSCustomObject]@{
            Issuer             = $issuer.TrimStart('"')
            Usages             = $Usages.ToString() -replace ',', ';'
            Expire_Date        = $FinalDate
            Days_Remaining     = "$DaysLeft"
            Status_Description = "About to expire"
        }
    }
}
$testDetail | Where {
    $_.Days_Remaining -lt 30 -and
    $_.Usages -ne "" 
} | Export-Csv -NoTypeInformation -Path 'C:\SECnology\Data\Files\other1\Certificate_Status.csv'

你要做的就是根据NotAfter属性进行筛选。根据您想要实现的目标,可能有多种选择:

# All certs which expiration date is before Friday, July 19, 2019 00:00:01
# This will include already expired certificates too
$_.NotAfter -le (Get-Date).Date.AddDays(30)

# All certs which expiration date is before Friday, July 19, 2019 00:00:00
# and after Wednesday, June 19, 2019 00:00:00
# This will include certificates that expired today
$_.NotAfter -le (Get-Date).Date.AddDays(30) -and $_.NotAfter -ge (Get-Date).Date

一般原则:

  1. 使用 -ge-gt 指定开始日期。区别仅在于您是否要包括确切的日期(所以相差一秒)
  2. 同样,使用-le-lt指定结束日期
  3. (Get-Date) 会给你当前的日期和时间,而 (Get-Date).Date),今天的日期在 00:00:00:
PS> Get-Date

Wednesday, June 19, 2019 12:16:57

PS> (Get-Date).Date

Wednesday, June 19, 2019 00:00:00

一旦您明确了确切的条件,请使用上述规则构建您的查询并将其添加到您的 Where-Object,如评论中提到的 @Ansgar

Where-Object {
  -not $_.PSIsContainer -and $_.NotAfter -le (Get-Date).Date.AddDays(30)
}
$Date = ((Get-Date).addmonths(1)).adddays(-(Get-Date ((Get-Date).addmonths(1)) -format dd))
$Certs = Get-ChildItem -Path Cert:\LocalMachine\My\ | select *
foreach($Cert in $Certs){
    if($Cert.NotAfter -le $date -and $Cert.NotAfter -ge (Get-Date)){
        $Data =
        [PSCustomObject]@{
            Issuer             = $Cert.Issuer
            Expire_Date        = $Cert.NotAfter
            Days_Remaining     = (New-TimeSpan -Start (Get-Date) -End $($Cert.NotAfter)).Days
            Status_Description = "About to expire"
        }
    }
}

供您试用或获取灵感的快速小脚本。这可以是当月 1 号的 运行,您将获得当月到期的证书,无论该月有 28 天、30 天还是 31 天。

解决方案是您 select 在 运行 日期和 $_.NotAfter 之间加上 -le/ge 日期。