September 14, 2020

Monitor server certificate

$servers=((Get-ADForest).Domains | %{ Get-ADDomainController -Filter * -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(60)}
}

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

}

}
$resultHtml = $result | ConvertTo-Html
Send-MailMessage -To "***recipient-email-address***" -From "***sender-email-address***" -Subject "***subject***" -Body "$resultHTML" -SmtpServer "***smtp-server***" -Port ***smtp-port*** -Priority High -BodyAsHtml
Write-Output $result

Set a scheduled task to run the powershell script above at a scheduled interval.

<Exec>
  <Command>powershell.exe</Command>
  <Arguments>C:\PSScripts\Cert-Check.ps1</Arguments>
</Exec>