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 | # set some constants for the script # min cert age is 60 days, print in red if the cert is going to expire in 60 days or less $minCertAge = 60 # set a timeout so the script doesnt slow down for incorrect URL $timeoutMs = 10000 # create an array of sites to check $sites = @( "https://url1", "https://url2", "https://url3" ) # disable certificate validation [Net.ServicePointManager]::ServerCertificateValidationCallback = {$true} # foreach site in the array, check the cert expiry foreach ($site in $sites) { # check the site by using .net httpwebrequest Write-Host Check $site -f Green $req = [Net.HttpWebRequest]::Create($site) $req.Timeout = $timeoutMs # try to get the page load try { $req.GetResponse() | Out-Null # get the certificate expiry, though this may error if the request failed $expDate = $req.ServicePoint.Certificate.GetExpirationDateString() # convert the string to a date # trim off the am/pm $certExpDate = [datetime]::ParseExact($expDate.substring(0, 17), "M/dd/yyyy H:mm:ss", $null) [int]$certExpiresIn = ($certExpDate - $(get-date)).Days # console write the status of our check if ($certExpiresIn -gt $minCertAge) { Write-Host The $site certificate expires in $certExpiresIn days [$certExpDate]`n -f Green } else { $message= "The $site certificate expires in $certExpiresIn days" Write-Host $message `n -f Red } } catch { #the page load didnt work, suspect invalid host or firewall Write-Host URL check error $site`: $_ -f Red } } |