Monitor URL Response Code

Websites availability monitoring is one of the most important things in IT monitoring, as many businesses rely on the websites that deliver their services to the customers. Or there are some internal applications that serves the IT infrastructure and it is website based and its availability is also important.

In this post we will go through how to get website response code through a PowerShell script

Firstly we will get the URL as an input to the script

param (
[string]$URL
)

Then, we will use try/catch PS command to get the response code no matter what it will be

We will use Invoke-WebRequest cmdlet with method get and keep the timeout as 45 second, then out of the result we will extract the response code (.statuscode part)

try{
$ResponseCode=(Invoke-WebRequest -Uri $URL -Method Get -TimeoutSec 45).statuscode

We will use if statement to evaluate the result and act accordingly

As a first validation we will check if the response code is null, and will return error message

    if ($ResponseCode -eq $null) {
return ("Error retrieving values")

Next evaluation will be for the accepted response code in this case we are monitoring 403 as healthy, you can change it to the wanted code

    } elseif ($ResponseCode -eq 403) {
return ("Website is Available, Response Code is " + $ResponseCode)

Last statement is for any other response code which is representing down status

    } else {
return ("The website is down returning "+$ResponseCode+ " Response Code")
}

Then, we have the catch command, in some response codes the PS will deal with them as errors like the 403, so we use catch command to get this response, then we will apply same if statement to output the result

} catch {
$statusCode = $.Exception.Response.StatusCode.value_
if ($statusCode -eq $null) {
return ("Error retrieving values")
} elseif ($statusCode -eq 403) {
return ("Website is Available, Response Code is " + $statusCode)
} else {
return ("The website is down returning "+$statusCode+ " Response Code")
}
}

You can apply this script to store results in needed areas or integrate it with monitoring tools if they lack this functionality.

Make sure to test the PS script to ensure it is giving the expected result before integrating it with other tools.

Full script below:

try{
$ResponseCode=(Invoke-WebRequest -Uri $URL -Method Get -TimeoutSec 45).statuscode
if ($ResponseCode -eq $null) {
return ("Error retrieving values")
} elseif ($ResponseCode -eq 403) {
return ("Website is Available, Response Code is " + $ResponseCode)
} else {
return ("The website is down returning "+$ResponseCode+ " Response Code")
}
} catch {
$statusCode = $.Exception.Response.StatusCode.value_
if ($statusCode -eq $null) {
return ("Error retrieving values")
} elseif ($statusCode -eq 403) {
return ("Website is Available, Response Code is " + $statusCode)
} else {
return ("The website is down returning "+$statusCode+ " Response Code")
}
}

Posted

in

by

Comments

Leave a comment