本地机器1个月内到期证书导出CSV异常问题求助
Fix: PowerShell Script Incorrectly Including Certificates Expiring Beyond 1 Month
Let's break down why your script is capturing certificates that expire more than a month out, and fix it up properly.
Key Issues in Your Original Code
- Uninitialized
$StartDatevariable: You use$StartDatein theNew-TimeSpancalculation but never assign it a value (like the current date). This leads to inconsistentDaysLeftvalues—PowerShell might default to an unexpected start time, causing some certificates with far-off expiration dates to incorrectly appear as expiring soon. - Filtering logic could be tightened: While you filter at the end, combining the expiration check earlier in the pipeline can reduce unnecessary object creation.
Corrected Script
$testPath = 'Cert:\LocalMachine\' $StartDate = Get-Date # Initialize to current date/time $testDetail = Get-ChildItem -Path $testPath -Recurse | Where-Object { -not $_.PSIsContainer } | ForEach-Object { $DaysLeft = ($_.NotAfter - $StartDate).Days $FinalDate = Get-Date $_.NotAfter -Format 'dd/MM/yyyy hh:mm' $Usages = ($_.Extensions | Where-Object { $_.KeyUsages }).KeyUsages if ($Usages -and $DaysLeft -le 30) { # Add expiration check here to skip non-qualifying certs early # Extract Issuer O and CN values, handle cases where one might be missing $issuerO = ([regex] 'O=([^,]+)').Match($_.Issuer).Groups[1].Value $issuerCN = ([regex] 'CN=([^,]+)').Match($_.Issuer).Groups[1].Value $issuerParts = @($issuerO, $issuerCN) | Where-Object { $_ } # Remove empty values $issuer = $issuerParts -join ', ' [PSCustomObject]@{ Issuer = $issuer.Trim('"') Usages = $Usages.ToString() -replace ',', ';' Expire_Date = $FinalDate Days_Remaining = "$DaysLeft" Status_Description = if ($DaysLeft -lt 0) { "Already expired" } else { "About to expire" } } } } $testDetail | Where-Object { $_.Usages -ne "" } | Export-Csv -NoTypeInformation -Path 'C:\SECnology\Data\Files\other1\Certificate_Status.csv'
What Changed & Why
- Added
$StartDate = Get-Date: This ensures we calculate days remaining from the current date, which is critical for accurate expiration checks. - Moved the expiration check into the
ForEach-Objectblock: We now only create objects for certificates that are expiring within 30 days (or already expired), which makes the script more efficient. - Improved issuer parsing: The original code could produce strings like
", CN=..."if theO=field was missing. The updated version filters out empty parts to avoid that. - Enhanced status description: Now differentiates between certificates that have already expired (
DaysLeft < 0) and those that are about to expire.
Quick Adjustment Tip
If you want to exclude already expired certificates and only include those expiring in the next 30 days, update the check to $DaysLeft -ge 0 -and $DaysLeft -le 30. Always test this script in a non-production environment first to confirm it works with your local certificate store.
内容的提问来源于stack exchange,提问作者mamadou
相关产品推荐
相关产品推荐

