One of my clients asked me how to check for expired certificates. This simple script opens the certificate store through the PS-drive CERT: and lists all certificates that are soon to expire. You can change the threshold to any value in the first line. Here’s the script:

$threshold = 30   #Number of days to look for expiring certificates
$deadline = (Get-Date).AddDays($threshold)   #Set deadline date
Dir Cert:\LocalMachine\My | foreach {
If ($_.NotAfter -le $deadline) { $_ | Select Issuer, Subject, NotAfter, @{Label="Expires In (Days)";Expression={($_.NotAfter - (Get-Date)).Days}} }
}

This script can also be used for several machines at once. Just add the Invoke-Command to the Dir command and make sure PowerShell remoting has been set up by using Enable-PSRemoting on the target servers. More info by running this PowerShell command: Get-Help about_remoting.

$threshold = 30   #Number of days to look for expiring certificates
$deadline = (Get-Date).AddDays($threshold)   #Set deadline date
Invoke-Command -ComputerName Srv01, Srv02 { Dir Cert:\LocalMachine\My } | foreach {
If ($_.NotAfter -le $deadline) { $_ | Select Issuer, Subject, NotAfter, @{Label="Expires In (Days)";Expression={($_.NotAfter - (Get-Date)).Days}} }
}

Dimitri

6 Comments on Check for certificate expiration with PowerShell (on multiple servers)

  1. Kunal Udapi says:

    Simple but good one, It was really helpful me to learn, specially got to know about about “Dir CERT:\”. good job.

  2. Pat Richard says:

    Great script. I think I’ll configure this as a scheduled task that will email me when a cert expires in x days. Thanks!

  3. Craig Aden says:

    This is so simple and I appreciate you for sharing such great script. Anyone related with this configuration will be pleased by finding this script. Thanks 🙂

  4. Shravan says:

    how to write PS Script to check the list of expired certs/certs nearing expiry in Microsoft Azure for a given azure subscription? Kindly share a sample script.