Rest API Authentication- Result Print Success or Failed 200/401

I’m trying to print Status code 200/401 in success and failed scenarios. I tried writing Power Shell Script, My script is working with status code 200. but if I want to failed my Token, `$StatusCode` is not printing 401.

I need some suggestions for print status code in both scenarios passing one parameters.

Here is my Script:

try {
if ($response = (Invoke-WebRequest @Params -ErrorAction Stop)){
$Token = (($response.Content) | convertFrom-Json).Token
}
} catch [System.Net.WebException] {
$StatusCode = "Status Code: $($_.Exception.Response.StatusCode.Value__) " ; $Message = " Message: $($_.Exception.Message))"
}

$StatusCode = "Status Code: $([int]$response.BaseResponse.statusCode)" "

$StatusCode is working for status code 200 only. but I want use same $Statuscode for failed status code 401.

So, $StatusCode should works for 200 and 401 and print accordingly.

Thanks.

 

Getting status codes are problematic and even more so with Invoke-RestMethod. It is a common ask\complaint to get this information in the exception. Using Invoke-WebRequest, you can try this:

https://stackoverflow.com/questions/42231486/capture-response-on-failed-401-invoke-webrequest