On Windows you can check two things with PowerShell: the certificates in the local store, and the certificate a server presents over the network.
Certificates in the local store
Everything in the machine's personal store that expires within 30 days:
Get-ChildItem Cert:\LocalMachine\My |
Where-Object { $_.NotAfter -lt (Get-Date).AddDays(30) } |
Select-Object Subject, NotAfter, Thumbprint
IIS uses this store. To see which certificate each binding uses, run netsh http show sslcert and match the
certificate hash to the thumbprint.
The certificate a server presents
function Get-CertExpiry([string]$Name, [int]$Port = 443) {
$tcp = [Net.Sockets.TcpClient]::new($Name, $Port)
try {
$ssl = [Net.Security.SslStream]::new($tcp.GetStream(), $false, { $true })
$ssl.AuthenticateAsClient($Name)
$cert = [Security.Cryptography.X509Certificates.X509Certificate2]::new($ssl.RemoteCertificate)
[pscustomobject]@{
Host = "${Name}:$Port"; NotAfter = $cert.NotAfter
DaysLeft = ($cert.NotAfter - (Get-Date)).Days; Issuer = $cert.Issuer
}
} finally { $tcp.Dispose() }
}
Get-CertExpiry example.com
Get-CertExpiry mail.example.com 993
The { $true } accepts any certificate, so you get the date even when it has already expired. It also means this
doesn't verify the chain or the name. Use the certificate check or openssl for that.
Several hosts
'example.com', 'www.example.com', 'mail.example.com:993' | ForEach-Object {
$name, $port = $_.Split(':')
if ($port) { Get-CertExpiry $name $port } else { Get-CertExpiry $name }
} | Sort-Object DaysLeft | Format-Table
Run it every week
Save the function and the list in a script and add a scheduled task:
$action = New-ScheduledTaskAction -Execute 'pwsh.exe' -Argument '-File C:\Scripts\cert-expiry.ps1'
$trigger = New-ScheduledTaskTrigger -Weekly -DaysOfWeek Monday -At 8am
Register-ScheduledTask -TaskName 'Certificate expiry' -Action $action -Trigger $trigger
The task needs a way to tell you, such as Send-MailMessage or a Teams webhook. On Linux and macOS, see
the shell script for many domains.