I need to make expiring certificates report, but have issue with replacing Certificate Expiration Date OID inside the csv exported from "certutil". ForEach-Object command don't recognize the column and replaces whole csv, though I can filter Template using 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"
Final Result
$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