How to check the website status code using PowerShell?

PowerShellMicrosoft TechnologiesSoftware & Coding

Website status code is meant to be the status of the website as if the website request from the client is successful or not if the website is available or any error on the webpage which is causing the handshake failed with the client.

There are various website status codes. Please refer to the below link for them.

https://en.wikipedia.org/wiki/List_of_HTTP_status_codes

To retrieve the status using PowerShell, we will first connect the webpage using the Invoke-WebRequest command and then we can use the property StatusCode. For example,

$req = Invoke-WebRequest -uri "https://theautomationcode.com"
$req

Output

StatusCode : 200
StatusDescription : OK
Content : <!DOCTYPE html>
         <html lang="en-US">
         <head>
         <meta charset="UTF-8">
         <meta name="viewport" content="width=device-width, initial-scale=1">
         <link rel="profile" href="http://gmpg.org/xfn/11">
         <script>...

We can see the status code in the output. Here 200 code means the connection is successful and no error on the webpage.

To retrieve only the status code,

$req.StatusCode

In the case of page unavailability, it throws the exception and the status code can not be captured, so we need to use a try/catch mechanism for handling the exception and generating the status code.

try{
   $req = Invoke-WebRequest -uri "https://theautomationcode.com/Unknownpage" Write-output    "Status Code -- $($req.StatusCode)"
} catch{
   Write-Output "Status Code --- $($_.Exception.Response.StatusCode.Value__) "
}

Output

Status Code --- 404
raja
Published on 18-Jan-2021 07:30:31
Advertisements