首页 > 解决方案 > 让证书在一个月或更短的时间内到期

问题描述

我想获取所有最多在一个月内到期的本地机器证书,并将它们的信息存储在一个.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'

标签: powershellcsvcertificate

解决方案


您要做的是根据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. 同样,使用-leor-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)
}

推荐阅读