I'm trying to get a 200 status code for a URL but I keep getting 0 instead. The url works, but the problem is it's a redirected URL. Even if I try the final URL after it redirects it still shows me a 0 status code.
How can I get the correct status code for a website that's down or up regardless of whether it's been redirected or not?
This is what I have now which works fine for regular URL's like http://google.com but not for redirected URL's. Unfortunately the urls I'm working with are private but it's in the format of http://example.com which winds up at https://example.com/index?redirectUrl=
If I run the PS script below with: .\CheckUrl.ps1 https://example.com/index?redirectUrl=
...it still fails to return a code of 200. The page comes up fine, whether I use the 1st url or the final redirected url but status code returns 0 which means it says the site is down and that's not true.
$url = $args[0]
function Get-WebStatus($url) {
try {
[Net.HttpWebRequest] $req = [Net.WebRequest]::Create($url)
$req.Method = "HEAD"
[Net.HttpWebResponse] $res = $req.GetResponse()
if ($res.StatusCode -eq "200") {
Write-Host "`nThe site $url is UP (Return code: $($res.StatusCode) - $([int] $res.StatusCode))`n"
} else {
Write-Host "`nThe site $url is DOWN (Return code: $($res.StatusCode) - $([int] $res.StatusCode))`n"
}
} catch {
Write-Host "`nThe site $url is DOWN (Return code: $($res.StatusCode) - $([int] $res.StatusCode))`n" -ForegroundColor Red -BackgroundColor Black
}
}
Get-WebStatus $url
Too long for a comment. Important:
$res = $req.GetResponse()
does not set any value into the$res
variable in thecatch
case (the$res
variable keeps unchanged).Output examples: