So I needed a script that I could run as a scheduled task that would alert me if there were any certificates that were due to expire soon from our servers. Some of our web servers will need their certificates renewing in the future that can’t be auto-renewed so thought this was the best time to put something in place to automatically alert the team when a certificate is due to expire and so action can be made ahead of time instead of when it happens.

I adapted my script  from the following blog article here, found that the script was buggy and would stall if a server was offline or if there was an issue with invoking the command remotely so I had introduced an if statement first to check if a server was online and to output the result to the console if so and to also turn the invoke command into a job and introduce a timeout so if for any issues the command block can’t be executed the script won’t hang and get stuck, it can just timeout. Lastly, I turned the object array into a string and did a check to see if the string was empty, null or had whitespaces and to do nothing if so and if the string has a value then the script will send an email with the certificates that are set to expire.

$servers= Get-ADComputer -Filter * -Searchbase "OU=Contoso Servers,OU=Contoso Computers,DC=contoso,DC=local" | Select-Object -Expandproperty Name

$result=@()
 
foreach ($i in $servers)
 


{

$ErrorActionPreference="SilentlyContinue"

if (Test-Connection -ComputerName $i -Count 1 -Quiet)
    {
    Write-Host "$i is online"
        $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(14)}} -erroraction $ErrorActionPreference
     

    } else {

        Write-Host "$i is offline"
    }
 



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

}
}

$smtpServer = "IP address or dns name of mail server"
$from = "certexpiry@chadd.ie"
$subject = "Alert: Certificate Expiry Notification"
$reportTo = "nath@chadd.ie"
 

$body = $result | Format-Table -HideTableHeaders | Out-String -Width 1000



IF([string]::IsNullOrWhiteSpace($body))
{Write-Host "No Certificates set to expire"}

else

{ 
Send-MailMessage -smtpServer $smtpServer -from $from -to $reportTo -subject $subject -body "This is a notification to inform that the following certificates will expire soon: $body" -priority High -ErrorAction SilentlyContinue 
 
}


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.