Hello, I’m writing a script that will check the availability/latency for a critical web page. It can alert when slow or down, but I would also like it to send an email when services are restored but I’m not sure how…
add-type @" using System.Net; using System.Security.Cryptography.X509Certificates; public class TrustAllCertsPolicy : ICertificatePolicy { public bool CheckValidationResult( ServicePoint srvPoint, X509Certificate certificate, WebRequest request, int certificateProblem) { return true; } } "@ [System.Net.ServicePointManager]::CertificatePolicy = New-Object TrustAllCertsPolicy #0 = false $hadError = 0 do { try { $times = measure-command {$result = Invoke-WebRequest -Uri "www.website.com" } if($times.totalseconds -gt 10) { $hadError = 1 #error occured, changed to 1 or true #send email because the times are too long $body = "Latency is currently high, last observed time was: $($times.totalseconds) seconds" #mail on success $smtpServer = "1.1.1.1" $msg = new-object Net.Mail.MailMessage $smtp = new-object Net.Mail.SmtpClient($smtpServer) $msg.From = "Events@domain.com" $msg.To.Add(@("ertuu85@domain.com")) $msg.Subject = "High API Latency" $msg.Body = $body $smtp.Send($msg) } } catch { $hadError = 1 #error occured, changed to 1 or true #send email because the times are too long $body = "Services are down`r`n`r`n Powershell Error: " + $(($error[0]).exception.message) #mail on success $smtpServer = "1.1.1.1" $msg = new-object Net.Mail.MailMessage $smtp = new-object Net.Mail.SmtpClient($smtpServer) $msg.From = "Events@domain.com" $msg.To.Add(@("ertuu85@domain.com")) $msg.Subject = "Down" $msg.Body = $body $smtp.Send($msg) } #somehow here it would be like if($haderror -eq 0) { #send email, all issues resolved } start-sleep 60 }until(1 -eq 2)
I would assume, in this case, $hadError would have to equal 1 or whatever if an error triggers but i’m not sure…because if an error doesnt trigger i dont want an email sending out every loop saying ‘all issues resolved’ or something.
Any help would be greatly appreciated