Archive for February, 2014

PowerShell to get remote website’s SSL certificate expiration

Posted in Monitoring, PowerShell, Scripting, Windows on 2014/02/04 by CRCerr0r

I recently needed to put together a PowerShell script that would check the expiration of some external and internal certificates for my company and let me know when they are close to expiring. Since some of the hosts were IP addresses, and some certs were not trusted by the machine running the check, I had to have a way to disable certificate chain validation (equivalent to the curl option -k). There are many ways to get web content in PowerShell, and some are more flexible than others… After some poking around, I put together the script below, combining examples from this post and this post.

$minimumCertAgeDays = 60
$timeoutMilliseconds = 10000
$urls = @(
) #disabling the cert validation check. This is what makes this whole thing work with invalid certs...
[Net.ServicePointManager]::ServerCertificateValidationCallback = {$true} foreach ($url in $urls)
Write-Host Checking $url -f Green
$req = [Net.HttpWebRequest]::Create($url)
$req.Timeout = $timeoutMilliseconds try {$req.GetResponse() |Out-Null} catch {Write-Host Exception while checking URL $url`: $_ -f Red} [datetime]$expiration = $req.ServicePoint.Certificate.GetExpirationDateString()
[int]$certExpiresIn = ($expiration - $(get-date)).Days $certName = $req.ServicePoint.Certificate.GetName()
$certPublicKeyString = $req.ServicePoint.Certificate.GetPublicKeyString()
$certSerialNumber = $req.ServicePoint.Certificate.GetSerialNumberString()
$certThumbprint = $req.ServicePoint.Certificate.GetCertHashString()
$certEffectiveDate = $req.ServicePoint.Certificate.GetEffectiveDateString()
$certIssuer = $req.ServicePoint.Certificate.GetIssuerName() if ($certExpiresIn -gt $minimumCertAgeDays)
{Write-Host Cert for site $url expires in $certExpiresIn days [on $expiration] -f Green}
{Write-Host Cert for site $url expires in $certExpiresIn days [on $expiration] Threshold is $minimumCertAgeDays days. Check details:`n`nCert name: $certName`nCert public key: $certPublicKeyString`nCert serial number: $certSerialNumber`nCert thumbprint: $certThumbprint`nCert effective date: $certEffectiveDate`nCert issuer: $certIssuer -f Red} rv req
rv expiration
rv certExpiresIn

Hope it saves someone some time… 🙂