What I am trying to do is restart a webpage once it is down. The services don't let us know that it is down. (Poor programming on the creator's side) We only know that the site is down by when it is down. There are no warnings. There are no error codes, it just goes down. I have been working with Invoke-WebRequest
.
$URL = "http://test.example.org"
while (!(Invoke-WebRequest -Uri $URL -UseBasicParsing -Method Head -ErrorAction SilentlyContinue)) {
Send-MailMessage -To "admin@example.org" -Body "$URL is down" -Subject "Site Down" -SmtpServer mail.example.org -From "SiteMonitor@Example.org"
Get-Service -ComputerName Example_Server -Name "Website Service" | Stop-Service
sleep 2
Get-Service -ComputerName Example_Server -Name "Website Service" | Set-Service -Status Running
sleep 2
"$(Get-Date)" >> C:\logs\ExampleDown.txt
if (Invoke-WebRequest -Uri $URL -UseBasicParsing -Method Head -ErrorAction SilentlyContinue) {
Send-MailMessage -To "admin@example.org" -Body "$URL is Up" -Subject "Site Up" -SmtpServer mail.example.org -From "SiteMonitor@Example.org"
}
}
The only problem I am having is whenever I do the Invoke-WebRequest
against the site when it is down, it produces an error message that stops the script from running each time. The error message is about the website cannot be resolved. I thought the while loop would treat it with a boolean and execute the while loop when the error message was presented because an error message is seen as false in if statements for the most part.