PowerShell for Non-N00bs: Certificate Files

Let's say we have a certfiicate file.  ("We have a certificate file."  Yuck-yuck, haw-haw.)  When does it expire?

PSH> $certObject = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2 $pathToCertFile;

PSH> $certObject.NotAfter
Wednesday, January 21, 2011 12:49:18 PM

PS> $certObject.NotAfter | Get-Member

   TypeName: System.DateTime

Name MemberType Definition

---- ---------- ----------

Add Method System.DateTime Add(TimeSpan value)

AddDays Method System.DateTime AddDays(Double value)

AddHours Method System.DateTime AddHours(Double value)

...

 

The Get-Member output shows $certObject.NotAfter to be a DateTime type, so we can compare it with today (Get-Date). This, coupled with New-TimeSpan allows us to test if a certificate is going to expire after a given time:

 

PS> $in90Days = (Get-Date) + (New-TimeSpan -Day 90)

PS> $in30Days = (Get-Date) + (New-TimeSpan -Day 30)

PS> $certObject.NotAfter -gt $in30Days

True

PS> $certObject.NotAfter -gt $in90Days

False