4

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.

NickG
  • 9,315
  • 16
  • 75
  • 115

2 Answers2

6

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
JPBlanc
  • 70,406
  • 17
  • 130
  • 175
  • OK: Looks like the complete solution for me is: – NickG Mar 05 '18 at 15:26
  • 5
    `(Get-ChildItem -Path cert:\LocalMachine\Webhosting | Where-Object {$_.Subject -match "example.com"} | Sort-Object -Property NotAfter -Descending | Select-Object -first 1).Thumbprint` – NickG Mar 05 '18 at 15:26
0

Seems sorting by NotAfter will lead to issues when using Letsencrypt while you still have a 1 year valid cert expiring after the Letsencrypt cert.

Made it work by sorting with NotBefore... haven't tested much though.

  • This does not provide an answer to the question. Once you have sufficient [reputation](https://stackoverflow.com/help/whats-reputation) you will be able to [comment on any post](https://stackoverflow.com/help/privileges/comment); instead, [provide answers that don't require clarification from the asker](https://meta.stackexchange.com/questions/214173/why-do-i-need-50-reputation-to-comment-what-can-i-do-instead). - [From Review](/review/late-answers/31507603) – Lee_Dailey Apr 13 '22 at 09:34