0

I have the below code to check website status in PowerShell version 2.

Begin {
    $webRequest = [Net.WebRequest]::Create("http://webdesa2:2003/Login.aspx");
}
Process {
    try {
        if ((($webRequest.GetResponse()).Statuscode) -as [int] -eq 200) {
            Write-Host "Site is Up";
            $webrequest.GetResponse();
        } else {
            Write-Host -Fore Red "Site is Down"
        }
    } catch {
        Write-Host -Fore Red "Site is Down"
    }
}

But I am getting the below output when executing the above code.

Exception calling "GetResponse" with "0" arguments: "The remote server returned an error: <401> Unauthorized."

This code worked good on websites where authentication is not required. My intention is to check if the site is up or not.

1 Answer 1

1

Catch the error and check if the status code is 401.

try {
    $response = $webRequest.GetResponse()
    if ($response.StatusCode.value__ -eq 200) {
        Write-Host 'Site is up.'
    } else {
        Write-Host 'Site is down.'
    }
} catch {
    if ($_.Exception.InnerException.Response.StatusCode.value__ -eq 401) {
        Write-Host 'Site is up.'
    } else {
        Write-Host 'Site is down.'
    }
}

Edit: Simplified code:

$validStatus = 200, 401

try {
    $status = $webRequest.GetResponse().StatusCode.value__
} catch {
    $status = $_.Exception.InnerException.Response.StatusCode.value__
}

if ($validStatus -contains $status) {
    Write-Host 'Site is up.'
} else {
    Write-Host 'Site is down.'
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.