powershellssl-certificatepowershell-3.0octopus-deploy

How can I get the most recent SSL certificate for a domain using PowerShell?


I'm trying to find the most recent certificate in the Web Hosting certificate store for a given domain (e.g. www.example.com)

It's easy enough to find any number of matching certificates, but how can I find only the most recent one, ordered by expiration date (furthest into the future)?

My existing code is:

(Get-ChildItem -Path cert:\LocalMachine\WebHosting 
   | Where-Object {$_.Subject -match "example.com"}).Thumbprint;

However this returns two certificates sometimes as usually the previous certificate (prior to a renewal) must be left in the certificate store for a short while.


Solution

  • You can try to sort then by the property notafter

    To have a look to all properties :

    (Get-ChildItem -Path cert:\LocalMachine\WebHosting | Where-Object {$_.Subject -match "example.com"}) | fl *
    

    To sort by notAfter property :

    (Get-ChildItem -Path cert:\LocalMachine\ca | Where-Object {$_.Subject -match ".*microsoft.*"}) | Sort-Object -Property NotAfter -Descending