Reputation: 145
I have this code that lists all local computer SSL certificates details and stores them in a csv
file. yet,There are some self-signed certificates that I found them useless so I want to exclude them from appearing and I could not get it right
Below is the code I wrote
$StartDate = Get-Date
$CertPath = 'Cert:\LocalMachine\'
$CertsDetail = Get-ChildItem -Path $CertPath -Recurse | Where-Object {
$_.PsIsContainer -ne $true} | ForEach-Object {
$DaysLeft = (New-TimeSpan -Start $StartDate -End $_.NotAfter).Days
if ($DaysLeft -lt 1) {
$Under30 = $true
$Expired = $true
$Text = "The Certificate is expired"
} elseif ($DaysLeft -lt 30) {
$Under30 = $true
$Expired = $false
$Text = "The Certificate is but valid about to expire"
} else {
$Under30 = $false
$Expired = $false
$Text = "The Certificate is still valid and not going soon to expire"
}
$FinalDate = Get-Date $_.NotAfter -Format 'dd/MM/yyyy hh:mm'
$Usages = ($_.Extensions | Where-Object {$_.KeyUsages}).KeyUsages
if ($Usages) {
$issuer = '{0}, {1}' -f
([regex] 'O=([^,]+)').Match($_.Issuer).Groups[1].Value,
([regex] 'CN=([^,]+)').Match($_.Issuer).Groups[1].Value
$issuer = $issuer.Trim(", ")
[PSCustomObject]@{
Text = $Text
Issuer = $issuer.TrimStart('"')
Subject = $_.Subject
ExpireDate = $FinalDate
DaysRemaining = $DaysLeft
Usages = $Usages.ToString() -replace ',', ';'
Under30Days = $Under30
Expired = $Expired
}
}
}
$CertsDetail | Where-Object {$_.DaysRemaining -lt 3650 -and $_.Usages -ne ""
} | Export-Csv -NoTypeInformation -Path 'C:\SECnology\Data\Utilities\Certificate_State.csv'
Upvotes: 0
Views: 382
Reputation: 174445
For self-signed certificates, the Subject
and Issuer
fields will be the same:
# Filter out self-signed certificates
Get-ChildItem -Path $CertPath -Recurse |Where { $_.Subject -ne $_.Issuer }
Upvotes: 1