user3649137
user3649137

Reputation: 33

" The remote server returned an error: (401) Unauthorized "

I am trying to verify if my URLs get a response. in other words, i am trying to check if the authentication has succeeded approaching the site.

I used:

$HTTP_Request = [System.Net.WebRequest]::Create('http://example.com')
$HTTP_Response = $HTTP_Request.GetResponse()
$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!"
}

$HTTP_Response.Close()

and I got the response:

The remote server returned an error: (401) Unauthorized.

but after that i got:

site is ok

Does that mean it's ok? If not, what is wrong?

Upvotes: 1

Views: 15052

Answers (2)

Raf
Raf

Reputation: 10107

You are getting OK because you rerun your command and $HTTP_Response contains an object from a previous, successful run. Use try/catch combined with a regex to extract correct status code(and clean up your variables):

$HTTP_Response = $null
$HTTP_Request = [System.Net.WebRequest]::Create('http://example.com/')
try{
    $HTTP_Response = $HTTP_Request.GetResponse()
    $HTTP_Status = [int]$HTTP_Response.StatusCode

    If ($HTTP_Status -eq 200) { 
        Write-Host "Site is OK!" 
    }
    else{
        Write-Host ("Site might be OK, status code:" + $HTTP_Status)
    }
    $HTTP_Response.Close()
}
catch{
    $HTTP_Status = [regex]::matches($_.exception.message, "(?<=\()[\d]{3}").Value
    Write-Host ("There was an error, status code:" + $HTTP_Status)
}

.Net HttpWebRequest.GetResponse() throws exceptions on non-OK status codes, you can read more about it here: .Net HttpWebRequest.GetResponse() raises exception when http status code 400 (bad request) is returned

Upvotes: 1

TomG
TomG

Reputation: 188

I think the following happens:

You are trying to query a web page using GetResponse(). This fails, so the following Statements run with the values you set in a previous run. This leads to the Output you described.

I personally tend to use the invoke-webrequest in my scripts. This makes it easier to handle Errors, because it supports all Common Parameters like Erroraction and so on.

Upvotes: 0

Related Questions