PowerShell and certutil.exe

An old customer got in contact recently. Could I help combine some PowerShell with certutil.exe to manipulate a certificate expiry report for a Windows Server 2008 R2 Certificate Authority?

Of course I could. Is the moon the Earth's natural satellite? Of course it is.

It's long been know that certutil can generate a report of expiring certs using the -view switch, with the -restrict parameter and the NotAfter attribute. For example, to get the certificates due to expire in the next month:

certutil -view -restrict "NotAfter<=1/02/2016,NotAfter>=1/01/2016" -out "RequesterName,CommonName,Certificate Expiration Date"

 

Could PowerShell inject the necessary dates for a reusable script or Advanced Function. Uh-huh. Yes, it could... here's the date injection:

$Before = Get-Date 01/02/2017

$Before = "$($Before.Day)/$($Before.Month)/$($Before.Year)"

$After = Get-Date 01/01/2016

$After = "$($After.Day)/$($After.Month)/$($After.Year)"

$Restrict = "NotAfter<=$Before,NotAfter>=$After"

certutil -view -restrict $Restrict -out "RequesterName,CommonName,Certificate Expiration Date"

 

We create a date range with $Before, i.e. certificates expiring before this date, and $After, i.e. certificates expiring after this date. These values are converted into something that certutil can understand - $Restrict. This is then used with the certutil -restrict parameter.

NB - the date format matches that of my region. You'll need to adjust accordingly...