PoshTip #14 – Find Certificates that are About to Expire

PoshTip #14 – Find Certificates that are about to expire

 

Here is a quick way to list the days remaining before the certificates on your servers are about to expire.

Below is my script.

It will check all your Active Directory computers and send certificates that expire in 90 days by email.

### CSS style
$a = @'
<style>
body { background-color:#FFFFFF;
       font-family:Tahoma;
       font-size:11pt; }
td, th { border:1px solid black; 
         border-collapse:collapse;
		 text-align:center;
		 background+color:#e0e0e0;
		 width:180px;}
th { color:#ffffff;
     background-color:darkblue;
	 text-align:center;}
table, tr, td, th { padding: 1px; margin: 0px }
table { margin-left:15px; }
</style>
'@
###

$tableau = @()
$threshold = 90   #Number of days to look for expiring certificates 
$liste = get-adcomputer -filter * | foreach {$_.Name}
$deadline = (Get-Date).AddDays($threshold)   #Set deadline date 
$tab=@()
$i = 0
Invoke-Command -ComputerName $liste { Dir Cert:\LocalMachine\My } | foreach { 
$i++
  If (($_.NotAfter -le $deadline) -and ((($_.NotAfter - (Get-Date)).Days) -ge 0)) { 
  $tab += $_ | Select Issuer, Subject, NotAfter, @{Label="Expires In (Days)";Expression={($_.NotAfter - (Get-Date)).Days}} 
        
  } 
} 

$tabsorted = $tab | sort "Expires*"

$body += $tabsorted | ConvertTo-HTML -head $a
$body += "<br/>"

### Send email
$anonUsername = "anonymous"
$anonPassword = ConvertTo-SecureString -String "anonymous" -AsPlainText -Force
$anonCredentials = New-Object System.Management.Automation.PSCredential($anonUsername,$anonPassword)
send-mailmessage -to "xxxx" -from "xxxx" -subject "Check certificates that expire in 90 days" -body ($body | out-string) -BodyAsHTML -SmtpServer "smtp.domain.com" -Credential $anonCredentials

You will get something like that :

certificat

About Nicolas 282 Articles
I work as an IT Production Manager, based in Paris (France) with a primary focus on Microsoft technologies. I have 10 years experience in administering Windows Servers. . I am a Microsoft MVP for Cloud & Datacenter Management. I also received the PowerShell Hero 2016 award by PowerShell.0rg. And finally, I am "MCSE: Cloud Platform and Infrastructure", "MCSA: Windows Servers", "Administering & Deploying SCCM", and CheckPoint CCSA certified.