Cyber Security

PowerShell: Alert me when Certificates expires soon

An expired certificate is a nuisance. In the case of web servers, this is indicated by the display of an untrusted connection when a user tries to open the web page. We will change this together in this article and make sure that we find certificates that will expire soon.

The Goal

In short, I will provide a few lines of code that retrieves all certificates from all domain-joined server that will expire in less or equal 30 days.

The result is an output which shows the server name, the certificate and the expiration date.

Unbenannt.PNG

The Code

The following code retrieves all Windows server by name. Then a remote connection is established to retrieve all certificates that will expire in less or equal 30 days. All information is collected in an object and the output will be shown in the console window.


$servers=(Get-ADComputer -Filter {operatingsystem -like '*server*'}).Name

$result=@()

foreach ($i in $servers)

{

$ErrorActionPreference="SilentlyContinue"

$a=Invoke-Command -ComputerName $i {Get-ChildItem Cert:\LocalMachine\My -Recurse |
Where-Object {$_ -is [System.Security.Cryptography.X509Certificates.X509Certificate2] -and $_.NotAfter -gt (Get-Date) -and $_.NotAfter -lt (Get-Date).AddDays(30)}

}

foreach ($c in $a) {

$result+=New-Object -TypeName PSObject -Property ([ordered]@{
'Server'=$i;
'Certificate'=$c.Issuer;
'Expires'=$c.NotAfter

})

}

}

Write-Output $result

Run this code in PowerShell ISE to test the functionality in your environment.

I also recommend to put the code into a scheduled task. This scheduled task should run regularly. Instead of writing the output to console you could send an E-Mail message.

If that’s the way you want it, just follow my article PowerShell: Alert me when Disk Space is running low on my Windows Servers (E-Mail Notification) where you can find a template for configuring E-Mail notification and creating a scheduled task.

See you next time with PowerShell and automation …

3 replies »

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

w

Connecting to %s