I’m back again with one more PowerShell script, this time getting certificate expiration warnings from Windows machines.
You can use the PowerShell script below to create a template and get warnings, critical, down etc. if a certificate is close to expiration or already is expired.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 |
#Create a object and open a connection to the destination server $ObjCertificates = new-object System.Security.Cryptography.X509Certificates.X509Store("\\${IP}\My","LocalMachine") #Opens the Cerificate store and places contents into the object as ReadOnly. $ObjCertificates.Open("ReadOnly"); #Get all certificates from the "local machine\personal". $Certificates = $ObjCertificates.Certificates | Where-Object {$_.Subject -ne $null}; #How many certificates looping through. $CertificateCounter = 0; #Foreach certificate. ForEach ($Certificate in $Certificates) { #Get the timespan for expire. $Expire = New-TimeSpan -Start (Get-Date) -End $Certificate.NotAfter; #Get subject name. $SubjectName = ($Certificate.Thumbprint); #If the certificate expiration date is higher than 2 days an lower than 60 days. If($Expire.Days -gt 2 -and $Expire.Days -le 60) { Write-Host ("Message." + $CertificateCounter + ": '" + $SubjectName + "' will expire within next 60 days."); Write-Host ("Statistic." + $CertificateCounter + ": " + $Expire.Days); #Exit with warning. Exit 2; } #If the certificate expiration date is higher than 0 days an lower than 2 days. Elseif($Expire.Days -gt 0 -and $Expire.Days -le 2) { Write-Host ("Message." + $CertificateCounter + ": " + $SubjectName + "' will expire within next 2 days."); Write-Host ("Statistic." + $CertificateCounter + ": " + $Expire.Days); #Exit with critical. Exit 3; } #If the certificate expiration date is lower than 0 days. Elseif($Expire.Days -lt 0) { Write-Host ("Message." + $CertificateCounter + ": '" + $SubjectName + "' is expired."); Write-Host ("Statistic." + $CertificateCounter + ": " + $Expire.Days); #Exit with warning. Exit 2; } #Else the certificate is good. Else { Write-Host ("Message." + $CertificateCounter + ": '" + $SubjectName + "' is not expired."); Write-Host ("Statistic." + $CertificateCounter + ": " + $Expire.Days); #Exit with OK. Exit 0; } #Add to the counter. $CertificateCounter++; } #If there is no certificate. If($CertificateCounter -eq 0) { Write-Host ("Message." + 0 + ": OK"); Write-Host ("Statistic." + 0 + ": 99999"); #Exit with OK. Exit 0; } |