Web

How to Check Website Status Using Powershell

Keeping tabs on the availability of a website is crucial for any business or individual relying on their online presence. A website going down can lead to lost revenue, missed opportunities, and a negative user experience. To help prevent these issues, I’ve written a PowerShell script that checks the status of a website and sends an alert email if the website is not reachable or returns a status other than 200 (OK). Here’s a breakdown of the script and how it works.


Complete Script

## How to Check Website Status Using Powershell ##

#░█████╗░██╗░░░██╗██████╗░███████╗██████╗░██╗██╗░░░░░██╗░░░░░░█████╗░
#██╔══██╗╚██╗░██╔╝██╔══██╗██╔════╝██╔══██╗██║██║░░░░░██║░░░░░██╔══██╗
#██║░░╚═╝░╚████╔╝░██████╦╝█████╗░░██████╔╝██║██║░░░░░██║░░░░░██║░░██║
#██║░░██╗░░╚██╔╝░░██╔══██╗██╔══╝░░██╔══██╗██║██║░░░░░██║░░░░░██║░░██║
#╚█████╔╝░░░██║░░░██████╦╝███████╗██║░░██║██║███████╗███████╗╚█████╔╝
#░╚════╝░░░░╚═╝░░░╚═════╝░╚══════╝╚═╝░░╚═╝╚═╝╚══════╝╚══════╝░╚════╝░

try{
    $siteUrl = "https://yoursite.com"
    $httpRequest = [System.Net.WebRequest]::Create($siteUrl)
    $httpResponse = $httpRequest.GetResponse()
    $httpStatus = [int]$httpResponse.StatusCode

    If ($httpStatus -eq 200) {
        Write-Host "Website is OK!"
    }
    Else {
        Throw "Website could be down, please check!"
    }

    If ($httpResponse -ne $null) { $httpResponse.Close() }
}
catch
{
    Write-Host $_
    $smtp = "smtp.yourdomain.com"
    $recipients = @("[email protected]","[email protected]")
    $to = $recipients
    $from = "[email protected]"
    $subject = "Website Unreachable!"  
    $body = "<p><span style=`"color: #ffffff; background-color: #ff0000; font-size: 20px;`"><strong>Website is unreachable! Please have a look!</strong></span></p>"
    Send-MailMessage -SmtpServer $smtp -To $to -From $from -Subject $subject -Body $body -BodyAsHtml

}

Script Breakdown

1. Try Block: Checking the Website Status

The script begins with a try block that attempts to check the status of the specified website. Here’s what each line does:

  • $siteUrl = "https://yoursite.com": This variable stores the URL of the website you want to monitor.
  • $httpRequest = [System.Net.WebRequest]::Create($siteUrl): A web request is created using the WebRequest class, targeting the specified URL.
  • $httpResponse = $httpRequest.GetResponse(): This sends the request and retrieves the response from the server.
  • $httpStatus = [int]$httpResponse.StatusCode: The status code from the response is stored in the $httpStatus variable. This status code tells you if the website is up and running. A code of 200 means “OK”, while other codes indicate various issues.
  • If ($httpStatus -eq 200): This checks if the status code is 200. If it is, the script prints “Website is OK!” to the console.
  • Else { Throw "Website could be down, please check!" }: If the status code is anything other than 200, an exception is thrown, triggering the catch block.
  • If ($httpResponse -ne $null) { $httpResponse.Close() }: This closes the response object to free up resources.

2. Catch Block: Sending an Alert Email

If the try block encounters an error (like a non-200 status code or an unreachable website), the script enters the catch block. Here’s what happens:

  • Write-Host $_: This outputs the error message to the console, which can help with troubleshooting.
  • Email Configuration:
    • $smtp = "smtp.yourdomain.com": The SMTP server used to send the email. This should be replaced with your actual SMTP server address.
    • $recipients = @("[email protected]","[email protected]"): This array holds the email addresses that will receive the alert. You can add as many recipients as needed.
    • $to = $recipients: Sets the recipients of the email.
    • $from = "[email protected]": The sender’s email address. It’s common to use a no-reply address for automated messages.
    • $subject = "Website Unreachable!": The subject of the alert email.
    • $body = "<p><span style="color: #ffffff; background-color: #ff0000; font-size: 20px;"><strong>Website is unreachable! Please have a look!</strong></span></p>": The email body, formatted in HTML to make it visually noticeable.
  • Send-MailMessage -SmtpServer $smtp -To $to -From $from -Subject $subject -Body $body -BodyAsHtml: This sends the email using the Send-MailMessage cmdlet. The -BodyAsHtml parameter ensures the email body is interpreted as HTML, not plain text.

How to Use This Script

  1. Specify the Site to Monitor: Replace "https://yoursite.com" with the URL of the website you want to monitor.
  2. Set Up the SMTP Server: Replace "smtp.yourdomain.com" with the address of your SMTP server. Ensure that the server is configured to send emails from your script’s environment.
  3. Update Email Addresses: Modify the $recipients array with the email addresses you want to receive the alerts. Also, update the $from address to an appropriate sender.
  4. Schedule the Script: You can schedule this script to run at regular intervals using Windows Task Scheduler, ensuring you are promptly notified if your website goes down.

Conclusion

This PowerShell script is a straightforward solution for monitoring the uptime of a website. By periodically running the script, you can stay informed of any issues with your site’s availability and address them before they impact your users. Adjust the script’s settings to fit your specific needs and keep your online presence in check.

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button