Did you know that you can use PowerShell to monitor your website and send you alarms when something goes wrong? We had availability issues with our community site and I was quite surprised that the 20-line (!) PowerShell script did the job!
Basically, all I had to do was use the Net.WebClient
object and its DownloadString
method to query the page (with some proxy handling code I got from Alexey Chuikov), and trap any exception which it generates when something goes wrong. The trap is using our internal relay server to send me and everyone who is involved in the site administration the email.
Here’s the code:
########################################################## # Test-Site - script to test web site availability # and notify in case of any issues # (c) Dmitry Sotnikov # https://dmitrysotnikov.wordpress.com ########################################################## function Test-Site { param($URL) trap{ "Failed. Details: $($_.Exception)" $emailFrom = "my.email@address.com" # Use commas for multiple addresses $emailTo = "my.email@address.com,another.admin@address.com" $subject = "PowerGUI.org down" $body = "PowerGUI web site is down. Details: $($_.Exception)" $smtpServer = "smtp.server.to.use.for.relay" $smtp = new-object Net.Mail.SmtpClient($smtpServer) $smtp.Send($emailFrom, $emailTo, $subject, $body) exit 1 } $webclient = New-Object Net.WebClient # The next 5 lines are required if your network has a proxy server $webclient.Credentials = [System.Net.CredentialCache]::DefaultCredentials if($webclient.Proxy -ne $null) { $webclient.Proxy.Credentials = ` [System.Net.CredentialCache]::DefaultNetworkCredentials } # This is the main call $webclient.DownloadString($URL) | Out-Null } Test-Site "http://powergui.org"
To test it you can obviously just put an invalid URL into the call.
Once I had the script running, I just set up a scheduled task in Windows Task Scheduler to run the script every 15 minutes:
One trick I learned from MoW and used in the task, was using the -command parameter (rather than just supplying the script) and including the exit $LASTEXITCODE
into the command, so the exit code from the PowerShell script gets registered as the scheduled task result.
So here’s the command-line I have scheduled:
c:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -NoProfile -Noninteractive -command ". c:\scripts\test-site.ps1; exit $LASTEXITCODE"
Works flawlessly! And can save you tons of money on a monitoring solution. Talk about ROI from learning PowerShell! 😉
Tags: .NET, Examples, Exchange, Internet, OpsMgr, PowerShell, Reporting, email, server management