#This is a combination of the two scripts credited below, I simply integrated some reporting logic. #Credits: #Boe Prox - https://mcpmag.com/articles/2014/11/04/expiring-certs-in-powershell.aspx #This guy - https://iamoffthebus.wordpress.com/2014/02/04/powershell-to-get-remote-websites-ssl-certificate-expiration/ #Check to see if existing results file exists, if so, delete. $checkrep = Test-Path ".\sslresults.txt" If ($checkrep -like "True") { Remove-Item ".\sslresults.txt" } New-Item ".\sslresults.txt" -type file #Script variables to determine expiration threshold, the number of milliseconds before moving onto the next URL, and the input file $minimumCertAgeDays = 60 $timeoutMilliseconds = 10000 $urls = Get-Content .\sslurl.txt #Primary script function [Net.ServicePointManager]::ServerCertificateValidationCallback = {$true} foreach ($url in $urls) { Write-Host Checking $url -f Red $req = [Net.HttpWebRequest]::Create($url) $req.Timeout = $timeoutMilliseconds try {$req.GetResponse() |Out-Null} catch { Write-Host Exception while checking URL $url`: $_ -f Red} [datetime]$expiration = $req.ServicePoint.Certificate.GetExpirationDateString() [int]$certExpiresIn = ($expiration - $(get-date)).Days $certName = $req.ServicePoint.Certificate.GetName() $certPublicKeyString = $req.ServicePoint.Certificate.GetPublicKeyString() $certSerialNumber = $req.ServicePoint.Certificate.GetSerialNumberString() $certThumbprint = $req.ServicePoint.Certificate.GetCertHashString() $certEffectiveDate = $req.ServicePoint.Certificate.GetEffectiveDateString() $certIssuer = $req.ServicePoint.Certificate.GetIssuerName() ##Report Logic #If the URL does not exist, it will return a value to the script saying that -736010 days remain. This logic specifically marks that item and moves on. if ($certExpiresIn -le -736010) { {Write-Host $url does not exist. -f Yellow} $output = "$url does not exist or is not responding.`r`n" Out-File -filepath .\sslresults.txt -inputobject $output -encoding ASCII -width 50 -Append } #If the URL is less than the number of acceptable expiration days but more than 0, the script will send a warning. if ($certExpiresIn -le $minimumCertAgeDays -and $certExpiresIn -gt 0) { {Write-Host Cert for site $url expires in $certExpiresIn days [on $expiration] -f Green} $output = "Notice - CERTIFICATE EXPIRING SOON - Cert for site $url expires in $certExpiresIn days [on $expiration]. Threshold is $minimumCertAgeDays days.`r`n" Out-File -filepath .\sslresults.txt -inputobject $output -encoding ASCII -width 50 -Append } #If the URL has expired (less than 0 days remaining), the script will flag accordingly. if ($certExpiresIn -lt 0 -and $certExpiresIn -gt -730160) { {Write-Host Cert for site $url expires in $certExpiresIn days [on $expiration] -f Green} $output = "**EXPIRED CERTIFICATE DETECTED** - Cert for site $url expires in $certExpiresIn days [on $expiration]. Threshold is $minimumCertAgeDays days.`r`n" Out-File -filepath .\sslresults.txt -inputobject $output -encoding ASCII -width 50 -Append } #If the cert is above the threshold, the script will not write to the file. else {Write-Host Cert for site $url expires in $certExpiresIn days [on $expiration] -f Green} #Uncomment this section for a full report that will show current, unexpired certificates# # $output = "Cert for site $url expires in $certExpiresIn days [on $expiration].`r`n" # Out-File -filepath .\sslresults.txt -inputobject $output -encoding ASCII -width 50 -Append rv req rv expiration rv certExpiresIn } Function Get-PKICertificates { [cmdletbinding( DefaultParameterSetName = 'PKI' )] param( [Parameter( Mandatory = $False, ParameterSetName = '', HelpMessage = "Computer to query certificates.", ValueFromPipeline = $True)] [string[]]$Computer = $Env:Computername, [Parameter( ParameterSetName = '', HelpMessage = "Acceptable values are 'LocalMachine','CurrentUser'. ` CurrentUser can only be access on local machine. LocalMachine can be accessed on local or remote machine.", ValueFromPipeline = $False)] [string][ValidateSet("LocalMachine","CurrentUser")] $StoreLocation = "LocalMachine", [Parameter( ParameterSetName = '', HelpMessage = "Acceptable values are 'AddressBook','AuthRoot','CertificateAuthority','Disallowed','My',` 'Root','TrustedPeople','TrustedPublisher'", ValueFromPipeline = $False)] [string][ValidateSet("AddressBook","AuthRoot","CA","Disallowed","My","Root","TrustedPeople","TrustedPublisher")] $StoreName = "My", [Parameter( Mandatory = $False, ParameterSetName = '', HelpMessage = "Acceptable values are 'ReadOnly','ReadWrite','MaxAllowed','OpenExistingOnly','IncludeArchived'", ValueFromPipeline = $False)] [string][ValidateSet("ReadOnly","ReadWrite","MaxAllowed","OpenExistingOnly","IncludeArchived")]$OpenFlag = "ReadOnly", [Parameter( Mandatory = $False, ParameterSetName = 'Expired', HelpMessage = "Show expired certificates", ValueFromPipeline = $False)] [switch]$ListExpired, [Parameter( Mandatory = $False, ParameterSetName = 'Expiring', HelpMessage = "Enter a number to list certificates expiring in given number of days", ValueFromPipeline = $False)] [Int32]$ExpiresIn ) Begin { #Create variable that holds the OpenFlags object Write-Verbose "Setting the OpenFlag variable" $ro=[System.Security.Cryptography.X509Certificates.OpenFlags]"$OpenFlag" #Create variable that holds the Store Location object Write-Verbose "Setting the Store Location variable" $cu=[System.Security.Cryptography.X509Certificates.StoreLocation]"$StoreLocation" } Process { ForEach ($c in $computer) { Try { #Check to see if computer is remote or local Write-Verbose "Checking to see if computer is local or remote." If ($Env:Computername -ne $c) { Write-Verbose "Computer is remote, verifying network connection" If (!(Test-Connection -ComputerName $c -Count 1 -Quiet)) { Write-Verbose "$($c): Unable to locate computer" Continue } Else { If ($StoreLocation -eq "CurrentUser") { Write-Verbose "Attempting to access Remote Computer with CurrentUser store name." Write-Verbose "Unable to access remote computer's CurrentUser store. ` `nYou can only do this with the LocalMachine store name." Continue } } } Switch ($StoreLocation) { LocalMachine { #Create new object and make connection to LocalMachine certificate store on computer Write-Verbose "Attempting to make connection to certificate store" $ce=new-object System.Security.Cryptography.X509Certificates.X509Store("\\$c\$StoreName",$cu) } CurrentUser { #Create new object and make connection to CurrentUser certificate store on computer Write-Verbose "Attempting to make connection to certificate store" $ce=new-object System.Security.Cryptography.X509Certificates.X509Store("$StoreName") } } #Open the store using defined flags Write-Verbose "Opening certificate store using defined OpenFlags" $ce.Open($ro) #Determine what will be displayed based on parameter set name Write-Verbose "Determining what certificates to display" Switch ($Pscmdlet.ParameterSetName) { "PKI" { #List all certificates in the store Write-Verbose "Listing all certificates in store" $ce.certificates } "Expired" { Write-Verbose "Listing all expired certificates" $ce.Certificates | ? {$_.NotAfter -le (Get-Date)} } "Expiring" { Write-Verbose "Listing certificates that expire in $ExpiresIn days" #Create a datetime object with the expiration threshold to compare against certificate expiration timestamp $deadline = (Get-Date).AddDays($ExpiresIn) $ce.Certificates | ? {$_.NotAfter -le ($deadline)} } } } Catch { #Write error that occurred with connection Write-Host -foregroundcolor Yellow "$($c): $($error[0])" } } } } $servers = get-content .\servers.txt Function List{ foreach ($server in $servers){ Get-PKICertificates -comp $server -StoreLocation LocalMachine -StoreName My -ExpiresIn 60 | Format-Table @{Label=”Server Name”;Expression={($server)}},FriendlyName, @{Label=”Expires In (Days)”;Expression={($_.NotAfter – (get-Date)).Days}} -auto } } List | Out-File .\servercerts.txt #Email Variables $date = Get-Date -Format "MMMM d, yyyy" $time = Get-Date -Format "hh:mmtt" $from = "ssl.report@domain.local" $to = "admin@mail.com" $subject = "SSL Report - $Date - $Time" $body = Get-Content .\sslresults.txt $SMTPServer = "smtp.local" $sslresults = get-content .\sslresults.txt $cerstore = get-content .\servercerts.txt #Mail action Send-MailMessage -from $from -to $to -subject $subject -body ($sslresults + $cerstore | out-string) -smtpserver $SMTPServer