"The remote server responded with an error: (401) Unauthorized"

I am trying to check if my URLs received a response. in other words, I am trying to verify that authentication to the site failed.

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 answer:

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

but after that I got:

website ok

Does this mean that this is normal? If not, what's wrong?

0
powershell
source share
2 answers

You get OK because you restart your command, and $HTTP_Response contains the object from the previous successful run. Use try / catch in combination with regex to extract the correct status code (and clear the 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 from status codes other than OK, you can read more about it here: .Net HttpWebRequest.GetResponse () throws an exception when the status code is http 400 (failed request)

+1
source share

I think the following happens:

You are trying to request a webpage using GetResponse (). This is not performed, therefore the following expressions are executed with the values ​​set in the previous run. This leads to the output you described.

I personally use invoke-webrequest in my scripts. This simplifies error handling, as it supports all common parameters, such as Erroraction, etc.

0
source share

All Articles