Checking Whether a Webpage is Up with Windows PowerShell

I ran into a situation where I needed to check a webpage at regular intervals to ensure it was up. I was working through Manning's PowerShell in a Month of Lunches and decided this would be a great chance to try out some PowerShell scripting.

Here were the requirements for my script:

  • Use variables so it is easy to change which webpage the script is monitoring
  • Checks whether a webpage is providing a 404 HTTP Status Code, or not
  • Records whether the webpage was up (no 404) or down (404) in a log file, with the date and time
  • When the webpage is down, a pop-up box appears to inform the user, and pressing okay brings the user to a relevant webpage (in my case, it was a WordPress admin panel)
  • Practice Using .NET Classes and Commands in PowerShell

This is the pop-up box that will disable is the webpage the script is monitoring is down.

This is an example of what the log file will look like.

Step 1: Variables

$URL = 'https://quotes.toscrape.com/pages/1/'
$WebsiteName = "Quotes to Scrape"
$AdminPanelUrl = "https://google.ca"
$Logfile = "C:\Logs\q2s.log"
$DateTime = Get-Date -format "yyyy-MM-dd HH:mm:ss"

Step 1 is to set up the variables the script will use. Since I wanted to copy and modify the script for multiple websites, all of these variables are at the top of the script.

  • $URL is for the website URL you would like to check
  • $WebsiteName is a string that contains the name of the website, which we will use in the pop-up box
  • $AdminPanelURL is a string to the URL you would like the user to be sent to when the website is down and they click "okay" on the pop-up box
  • $Logfile is the path where the script will write the up or down status of the website too
  • $DateTime is used to get the current date and time, which is written to the log file

Step 2 : Getting the Status Code of a Webpage

# Create the request.
$HTTP_Request = [System.Net.WebRequest]Create($URL)

# Get the response, catching an error and reporting the website as down if GetReponse() throws any error.
try {
    $HTTP_Response = $HTTP_Request.GetResponse()
}
catch {
    Write-Host " $($WebsiteName) Is Down" "Go Check $($WebsiteName)."
    Write-Host "Down"
    exit
}

# Get the HTTP Status Code as a integer
$HTTP_Status = [int]$HTTP_Response.StatusCode

if ($HTTP_Status -eq 404) {
    Write-Host " $($WebsiteName)Is Down" "Go Check $($WebsitName)."
    Write-Host "Down"
}
else {
    Write-Host "Up"
}

# Clean up and close the request.
$HTTP_Response.Close()

After declaring the variables above, this is where most of the action is. On line 2, the script uses the .NET Class System.Net.WebRequest and a .NET Method Create() to create a new WebRequest object with our $URL inside it.

Then on line 6, we use GetResponse() to get the HTTP response for the requested webpage. On line 15 we get the HTTP Status Code, which we then check with an if statement on line 17 if it is equal to 404.

The script currently uses Write-Host command temporarily, so you can copy and paste this code into Visual Studio Code, or another IDE, and run it right now.

Step 3: Functions for the Prompt and Log File

#This function wraps the creation of a simple pop-up box, which is used twice in the program
function Create-PopUpBox($text,$title){
    $msgBoxInput = [System.Windows.MessageBox]Show($text,$title,"OkCancel", "Error")
    switch ($msgBoxInput) {
        'Ok' {
            Start-Process $AdminPanelUrl
        }
        'Cancel' {
        }
    }
 }

Now we need to create two helper functions, which go between our variables in Step 1, and our main code in Step 2. This first function is to create a pop-up box with whatever text and title we need. This again uses .NET Classes and Commands to create the pop-up box.

Note that Start-Process is used here to open our Admin Panel URL after we click the okay button. This is so when the website is down, we can bring ourselves to the admin panel, to reset the page.

 #This function writes the current date and time + the passed in log string to the path specified in $Logfile.
 function Write-LogFile ($logstring) {
    Add-Content $Logfile -value "$($datetime) - $($logstring)"
}

This is our second function, which is used to write to a log file. Since the path and formatting of the log file will be consistent, our function only expects a string, which will be "Up" or "Down" depending on the status of the webpage.

Step 4: Updating the Main Program

# Create the request.
$HTTP_Request = [System.Net.WebRequest]Create($URL)

# Get the response, catching an error and reporting the website as down if GetReponse() throws any error.
try {
    $HTTP_Response = $HTTP_Request.GetResponse()
}
catch {
    Create-PopUpBox "$($WebsiteName) Is Down" "Go Check $($WebsiteName)"
    Write-LogFile "Down"
    exit
}

# Get the HTTP Status Code as a integer
$HTTP_Status = [int]$HTTP_Response.StatusCode

if ($HTTP_Status -eq 404) {
    Create-PopUpBox "$($WebsiteName) Is Down" "Go Check $($WebsiteName)"
    Write-LogFile "Down"
}
else {
    Write-LogFile "Up"
}

# Clean up and close the request.
$HTTP_Response.Close()

This is the main part of the script from Step 2 modified to use the functions from Step 3. Lines 9 and 18 use the Create-PopUpBox function, while lines 10, 19, and 22 use the Write-LogFile function. These replace all the Write-Host commands from the previous version, completing the script.

Conclusion

That's it! Now when the script is run, it will go out and check the webpage specified to see whether the page returns a 404 Status Code, or not, and notify the user. You can check out a complete version of the script here. You can use Window's Task Scheduler to run this script every hour, or more frequently.

It is possible to write a much shorter program using Invoke-WebRequests, this script uses the .NET System.Net.WebRequest as a way to practice the use of .NET objects within PowerShell.