Monday, May 18, 2009

Powershell script to check for expired certificates

Had a request today to produce a report on all expired certificates on a server.At first I thought this would difficult but it turns out to be quite simple.

Once you get to the power shell the first thing you need to move into the certificate store.

cd cert:

You could list all certificates by simply running gci -recurse. For this exercise I was only interested in self sign certificates issued by "MyCompany"

gci -recurse | where {$_.Issuer -like "*MyCompany*"} . This command will produce a list of certificates where the issuer contains MyCompany so "Super MyCompany" or "MyCompany is tops" will be in the results list.

We can then reduce the output by only asking for only properties we're interested in. In this case instead of using format-table I've outputed the results to html using the convertTo-html cmdlet.
gci -recurse | where {$_.Issuer -like "*MyCompany*"} |ConvertTo-Html Subject, Issuer, Thumbprint, FriendlyName, Notbefore, Notafters |set-content c:\certs\certsreport.htm

This is all you need but if you want a report of already expired certificates we can filter the results by excluding any certificates the have expiry date less than today.

To do this set variabe with the value of todays date this can done with the following command.

$date=date

Here's the full code to produce html report of all expired certificates. Make sure the c:\certs dir exists.

cd cert:
$date=date
gci -recurse | where {$_.Issuer -like "*MyCompany*"} |where {$_.NotAfter -gt $date} |ConvertTo-Html Subject, Issuer, Thumbprint, FriendlyName, Notbefore, Notafters |set-content c:\certs\certsreport.htm

If want to send this in a email as an attachment here's the code.

cd cert:
$date=date
gci -recurse | where {$_.Issuer -like "*Clayton*"} |where {$_.NotAfter -gt $date} |ConvertTo-Html Subject, Issuer, Thumbprint, FriendlyName, Notbefore, Notafters |set-content c:\certs\certsreport.htm

$filename = “c:\certs\certsreport.htm”
$smtpServer = “smtp.cu.claytonutz.com”

$msg = new-object Net.Mail.MailMessage
$att = new-object Net.Mail.Attachment($filename)
$smtp = new-object Net.Mail.SmtpClient($smtpServer)

$msg.From = “steve@mycompany.com”
$msg.To.Add(”destination@mycompany”)
$msg.Subject = “Certs Reports”
$msg.Body = “Expired Certificates”
$msg.Attachments.Add($att)

$smtp.Send($msg)

Regards,

Steve