Wednesday, November 27, 2013

Everyday Powershell - Part 10 - Powershell to check if certificates are going to expire

This is the next part in an ongoing series about Powershell. You may have heard about how awesome Powershell is but have struggled to find ways to make it useful in your day to day work. That's what this series is going to address. It'll provide scripts and knowledge to address practical everyday problems

This weeks script was a request from a reader. He wanted a reminder of when certificates were going to expire on his server. Having felt the stress of running through Extended Validation for production certificates with only hours to spare before expiry, the need for such a script was obvious.

$days = 60
$certs = $null
$certs = Get-ChildItem -Path cert: -Recurse -ExpiringInDays $days | select Subject, thumbprint, notafter
if ($certs -ne $null)
{
    [string]$body = $certs | convertto-html -Body $_
    Send-MailMessage -To someone@someserver.com -From someone@someserver.com -Subject "Certificates Expiring in $days days" -SmtpServer somemailserver -BodyAsHtml $body
}

The great thing is it's bloody easy with Powershell 4. If you are not up to date you should be it's easy!

Just schedule this to run at a regular schedule if only there was some kind of guide to do that in powershell.

Requests are fun! If you have a need for a script to do anything post a comment or send me tweet @benhaslett I'd be happy to give it a crack! Or at the very least I can Google around and see if someone has done something similar!

3 comments:

  1. We have loads of systems utilising certs and I cbf'd setting this up for each, so I am going to GPO it as a weekly task. Because it will be in bulk, we also have a problem with the powershell version. The windows management framework pack shouldn't be installed on many systems... so if I need a new PS version I have to hand-hold them. I have modified the script slightly to run on PS v2 systems and also a couple of minor preferences.
    "
    $days = 60
    $future = (get-date).adddays($days)
    $server = hostname
    $certs = $null
    $certs = Get-ChildItem -Path cert:\LocalMachine\My | where {$_.NotAfter -gt (get-date) -and $_.NotAfter -lt $future} | select Subject, thumbprint, notafter
    if ($certs -ne $null)
    {
    [string]$body = $certs | convertto-html -Body $_
    Send-MailMessage -To someone@someserver.com -From someone@someserver.com -Subject "Certificates Expiring within $days days on Server $server" -SmtpServer somemailserver -BodyAsHtml $body
    }
    "

    ReplyDelete