Get expiry date of certificate files

I’ve been recently tasked to check when the certificates issued by our CA expire.
All these files are stored in a secure location on a central shared folder and have the same password.

I first tried the Get-PfxCertificate cmdlet. It’s working correctly and prompts for the password.
But it’s somehow limited as one cannot specify the password as an argument. In other words, it isn’t designed for my automation needs 😉

The Get-PfxCertificate cmdlet produces a System.Security.Cryptography.X509Certificates.X509Certificate2 .net object that has many constructors that can be found on the following MSDN page:
X509Certificate2 Class

Constructors can also be listed like this:

$a.GetType().Getconstructors()| % {$_.ToString() }

I chose the following constructor:

X509Certificate2(String, String) Initializes a new instance of the X509Certificate2 class using a certificate file name and a password used to access the certificate.

Here’s how I inventoried all certificates expiry date and exported the result to a CSV file:

# Get the list of all files
$allcertificates =  Get-ChildItem -Path \\server\share\path-of-certificates-folder -Include *.p12 -Recurse

# Create an array with the filename and its expiry date
$results = foreach ($cert in $allcertificates) {

    # Prepare a hashtable
    $HT = @{
        TypeName = 'System.Security.Cryptography.X509Certificates.X509Certificate2';
        ArgumentList = @($cert.FullName,"MyVeryComplexClearTextPassword");
    # Output
	New-Object -TypeName psobject -Property @{
	    FileName = $cert.Name ;
	    ExpiryDate =  (New-Object @HT).NotAfter;

# See what certificates expire in the next two years
$results | ? { $_.ExpiryDate -lt (Get-Date).AddMonths(24)  }

# Export sorted results to CSV
$results | Sort ExpiryDate | Export-Csv -Path .\inventory.2013.11.26.csv

One thought on “Get expiry date of certificate files

  1. If you are only going to use this on one or limited servers the likely you best (easiest, quickest) bet is to download and use the OpenSSL tool / utility.

    PowerShell can of course drive that, but the tool works well and already does most of what people want for your stated goal.

    I recently wrote my own custom C# program to do this but I needed it to run on any of thousands of servers in our estate so it was impractical to add the OpenSSL tools to all of those.

    We did end up using the OpenSSL tool on the Linux servers however since they mostly already had it available.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.