powershell - 让证书在一个月或更短的时间内到期
问题描述
我想获取所有最多在一个月内到期的本地机器证书,并将它们的信息存储在一个.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
一般原则:
- 使用
-ge
或-gt
指定开始日期。区别仅在于您是否要包含确切的日期(因此相差一秒) - 同样,使用
-le
or-lt
指定结束日期 (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)
}
推荐阅读
- reactjs - React:导入函数并将状态传递给它不起作用
- c++ - OpenCV C++ 3 Dimensional Mat 数据访问错误值
- reactjs - useEffect 导致无限循环
- java - 如何按名称过滤Java中的多个文件?
- javascript - react如何在useCallback中保持变量值?
- javascript - 如果连续单击两个相同的名称,如何使每两个相同的名称保持红色?
- python - 绘制排序数据
- javascript - Javascript对象保留“旧”属性,不能覆盖?
- swift - 如何更改 SpriteKit 中精灵的触摸偏移量?
- python - 在 pytorch 中使用量化模型没有性能提升