Srayan Guhathakurta
Srayan Guhathakurta

Reputation: 556

Detecting SSL certificates due for expiry

I have *.cer files that are a part of a project that reside on my local disk. They are not installed in my system.

Say the location of certs is: C:\Users\wrick\Source\Repos\MyProject\Src\Certificates\

Now I want to run a PowerShell script that will give me the list of *.cer files that are due for expiry in 90 days.

This is what I wrote:

Get-ChildItem -Recurse -Path C:\Users\wrick\Source\Repos\MyProject\Src\Certificates\ |
    Select-Object -Property PSChildName, Subject,
        @{n=’ExpireInDays’;e={($_.notafter – (Get-Date)).Days}} |
    Where-Object {$_.ExpireInDays -lt 90 -and $_.Extension -like "*.cer"}

I have added the $_.Extension -like "*.cer" part because the cert directory has some other script files too. I am not getting any output when I run this script.

Upvotes: 0

Views: 1336

Answers (1)

StephenP
StephenP

Reputation: 4081

You can still do this in powershell, just dip into the .Net framwork and use the System.Security.Cryptography.X509Certificates.X509Certificate class.

#Filter for *.cer files as early as possible
Get-ChildItem -Recurse -Path C:\Users\wrick\Source\Repos\MyProject\Src\Certificates\ -Filter *.cer |
#grab the full file path, read in the cert, get the expiration date and convert to a datetime object
select FullName,@{name='ExpirationDate';e={[DateTime]([System.Security.Cryptography.X509Certificates.X509Certificate2]::CreateFromCertFile($_.FullName).GetExpirationDateString())}} |
#filter for those that expire within 90 days
Where-Object {$_.ExpirationDate -lt [DateTime]::Today.AddDays(90)}

Upvotes: 3

Related Questions