How to check response code from a website using PowerShell
In this post we will discuss about how to check the response code from a website. In this article, we’re going to cover how to build a PowerShell function that will query a specific URL and attempt to find out if that URL is working fine or not. To get started, let’s construct a function for this task called CheckSiteURLStatus with a single parameter called URL.
Net.WebReques makes a request to a Uniform Resource Identifier (URI). This is an abstract class.
Using Net.WebRequest class (which is under the System.Net namespace), we get a response from a web server. Unlike the Net.WebClient class, you will not be able to download the site page. However, using Net.WebRequest class, you can get a response code and also see what type of web server is being used to host the site. The WebRequest class has a static method called Create in which we can pass a URL to invoke a HTTP, We’ll add the code to create the request into our function as shown below.
[string] $_URL = 'https://dotnet-helpers.com' function CheckSiteURLStatus($_URL) { try { $request= [System.Net.WebRequest]::Create($_URL) $response = $request.getResponse() if ($response.StatusCode -eq "200") { write-host "`nSite - $_URL is up (Return code: $($response.StatusCode) - $([int] $response.StatusCode)) `n" -ForegroundColor green } else { write-host "`n Site - $_URL is down `n" ` -ForegroundColor red } } catch { write-host "`n Site is not accessable, May DNS issue. Try again.`n" ` -ForegroundColor red } } CheckSiteURLStatus $_URL
Based on the response code, the condition will execute and write on the console.Finally, we’ll need to dispose of the response after we’re done to clear it from memory which would finish it off to make it look like this:
OUTPUT
What do you think?
I hope you have idea of how to check the Website status using Powershell script. I would like to have feedback from my posts readers. Your valuable feedback, question, or comments about this article are always welcome.
Hi Vediyappan,
You can add this script in TaskScheduler for monitoring every 10 min (any interval of time) and integrate the sending mail concept in the script. Sample is shown in the below article. https://dotnet-helpers.com/powershell/how-to-use-powershell-to-detect-logins-and-alert-through-email-using-sendgrid/
How to get the Emial alerts when the page is down automatically
Good work, thanks!