我需要制作過期證書報告,但在替換從“certutil”匯出的 csv 中的證書過期日期 OID 時遇到問題。ForEach-Object 命令無法識別列并替換整個 csv,但我可以使用 Where-Object 過濾模板。
$currdate = Get-Date
$date = (Get-Date).AddYears(2)
$template = "RDP|IIS"
$path = "C:\Temp\"
if(!(test-path $path))
{
New-Item -ItemType Directory -Force -Path $path
}
certutil -view -restrict Disposition=20 -out "Request.CommonName,NotAfter,CertificateTemplate" csv | Out-File $path\ExpiredCerts.csv
Import-Csv $path\ExpiredCerts.csv | ForEach-Object {$_.'Certificate Template' -replace "^\d.* ",""}
Import-Csv $path\ExpiredCerts.csv |Where-Object {$date -gt $_.'Certificate Expiration Date' -and $currdate -lt $_.'Certificate Expiration Date' -and $_.'Certificate Template' -match $template} | ConvertTo-Html -Head $Header | Out-File $path\ExpiredCerts.htm
CSV檔案
"Request Common Name","Certificate Expiration Date","Certificate Template"
"*.piltover1.com","11/06/2022 13:08","1.3.6.1.4.1.311.21.8.9809061.13872499.9847428.7216726.9936658.242.11024705.6775621 IIS"
"*.piltover2.com","11/06/2022 13:08","1.3.6.1.4.1.311.21.8.9809061.13872499.9847428.7216726.9936658.242.11024705.6775621 IIS"
"*.piltover3.com","11/06/2022 13:08","1.3.6.1.4.1.311.21.8.9809061.13872499.9847428.7216726.9936658.242.11024705.6775621 IIS"
最后結果
$currdate = Get-Date
$date = (Get-Date).AddDays(30)
$template = "RDP|IIS"
$path = "C:\Temp\"
if(!(test-path $path))
{
New-Item -ItemType Directory -Force -Path $path
}
certutil -view -restrict Disposition=20 -out "Request.CommonName,NotAfter,CertificateTemplate" csv | Out-File $path\ExpiredCerts.csv
$data = Import-csv $path\ExpiredCerts.csv
foreach ($item in $data) {
$item.'Certificate Template' = ($item.'Certificate Template' -split ' ')[-1]
}
$data | Where-Object {$date -gt $_.'Certificate Expiration Date' -and $currdate -lt $_.'Certificate Expiration Date' -and $_.'Certificate Template' -match $template} |
ConvertTo-Html -Head $Header | Out-File ExpiredCerts.htm
uj5u.com熱心網友回復:
您可以這樣做以從“證書模板”列中洗掉 OID,無需將該資料寫入檔案并重新匯入,即可從中創建 HTML 檔案。
這假設您已經在 CSV 檔案中擁有來自 certutil 的原始資料:
$data = Import-Csv -Path (Join-Path -Path $path -ChildPath 'ExpiredCerts.csv')
# remove OIDs in column 'Certificate Template'
foreach ($item in $data) {
$item.'Certificate Template' = ($item.'Certificate Template' -split ' ')[-1]
}
# filter the data you need based on expiration date and template
$data | Where-Object {$date -gt (Get-Date $_.'Certificate Expiration Date') -and
$currdate -lt (Get-Date $_.'Certificate Expiration Date') -and
$_.'Certificate Template' -match $template} |
ConvertTo-Html -Head $Header | Set-Content (Join-Path -Path $path -ChildPath 'ExpiredCerts.htm')
PS 我Set-Content贊成使用,Out-File因為我們不知道您使用的是哪個版本的 PowerShell。在 PS 7.x 版中, Out-File 的默認編碼是utf8NoBOM,而在 PS 5.1 版中,默認檔案編碼是unicode(= UTF16-LE) 這可能不是您想要的。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/389641.html
上一篇:執行后運行點源腳本時出錯
