You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

本地机器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

  1. Uninitialized $StartDate variable: You use $StartDate in the New-TimeSpan calculation but never assign it a value (like the current date). This leads to inconsistent DaysLeft values—PowerShell might default to an unexpected start time, causing some certificates with far-off expiration dates to incorrectly appear as expiring soon.
  2. 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-Object block: 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 the O= 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 09:26:58