PowerShell script to check the status of a URL
You can try this:
function Get-UrlStatusCode([string] $Url)
{
try
{
(Invoke-WebRequest -Uri $Url -UseBasicParsing -DisableKeepAlive).StatusCode
}
catch [Net.WebException]
{
[int]$_.Exception.Response.StatusCode
}
}
$statusCode = Get-UrlStatusCode 'httpstat.us/500'
I recently set up a script that does this.
As David Brabant pointed out, you can use the System.Net.WebRequest
class to do an HTTP request.
To check whether it is operational, you should use the following example code:
# First we create the request.
$HTTP_Request = [System.Net.WebRequest]::Create('http://google.com')
# We then get a response from the site.
$HTTP_Response = $HTTP_Request.GetResponse()
# We then get the HTTP code as an integer.
$HTTP_Status = [int]$HTTP_Response.StatusCode
If ($HTTP_Status -eq 200) {
Write-Host "Site is OK!"
}
Else {
Write-Host "The Site may be down, please check!"
}
# Finally, we clean up the http request by closing it.
If ($HTTP_Response -eq $null) { }
Else { $HTTP_Response.Close() }
For people that have PowerShell 3 or later (i.e. Windows Server 2012+ or Windows Server 2008 R2 with the Windows Management Framework 4.0 update), you can do this one-liner instead of invoking System.Net.WebRequest
:
$statusCode = wget http://stackoverflow.com/questions/20259251/ | % {$_.StatusCode}