Powershell script to find currently bound expiring certificates in IIS
Asked Answered
C

1

6

I am trying to get a working script to check for expiring SSL certificates in IIS. There are many similar entries with simply getting the list of expiring installed certificates but I need some extra logic.

I need to know all certificates expiring within x days that are A) currently bound to a website and B) that website must have a state of "Started"

I have certain information gathered (below) but I am having trouble correlating them so they only give me the expiring certs I need. To add to the complexity, I can't simply look for the site name in the CN in the subject of the certificates because there are many hundreds of certs installed and it is not uncommon for 1 or more older certificates for the same site to still be installed. That being said, they have the same subject. I will need to compare thumbprints but getting the thumbprint by simply specifying the site name is proving to be difficult.

Some of the code to gather various relevant details is as follows:

ActiveSites = get-website | where {$_.State -eq "Started"}
$DaysToExpiration = 7
$InstalledCerts = gci cert:\localmachine\my
$ExpiringCerts = $InstalledCerts | Where {(($_.NotAfter - (Get-Date)).Days) -lt $DaysToExpiration}
Currajong answered 24/4, 2013 at 1:5 Comment(0)
I
8

A list of the certificates bound to websites can be obtained from the IIS: provider:

Get-ChildItem IIS:SSLBindings

Try this:

$DaysToExpiration = 7

$expirationDate = (Get-Date).AddDays($DaysToExpiration)

$sites = Get-Website | ? { $_.State -eq "Started" } | % { $_.Name }
$certs = Get-ChildItem IIS:SSLBindings | ? {
           $sites -contains $_.Sites.Value
         } | % { $_.Thumbprint }

Get-ChildItem CERT:LocalMachine/My | ? {
  $certs -contains $_.Thumbprint -and $_.NotAfter -lt $expirationDate
}
Impair answered 24/4, 2013 at 7:49 Comment(2)
You, sir, are a genius. $_.Sites.Value was exactly what I needed. I couldn't figure out how to reference that.Currajong
Get-ChildItem IIS:SSLBindings returns me "Cannot find drive. A drive with the name 'IIS' does not exist" even tho I am importing WebAdministration Module.Yager

© 2022 - 2024 — McMap. All rights reserved.