Invoke-WebRequest does not return the expect status code

Hi All

I want to make script to check our local apps I do not have permission to all of them but I just want to get the status of each app

I use this command

Invoke-WebRequest -Uri $WEBAPP -Method get | select statuscode

when I send the request for the apps I do not have access I got this error

 

 

Invoke-WebRequest : Server Error
401 - Unauthorized: Access is denied due to invalid credentials.
You do not have permission to view this directory or page using the credentials that you supplied.
At line:1 char:1
+ Invoke-WebRequest -Uri $WEBAPP -Method get | select statuscode
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-WebRequest], WebException
+ FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand

I know I just want to get 401 under status code instead of this complete error , I do agree with powershell I do not have access

just give 401

 

I have come up with this issue before. Unfortunately its always going to error rather than just return the error code. When I was investigating it, I came across this post of Stack Overflow which solved it for me:

https://stackoverflow.com/questions/19122378/powershell-web-request-without-throwing-exception-on-4xx-5xx

 

Hope it helps.

 

Thanks A lot Alex you made my day

I got the status code as expected

I’m sharing the code (the output on the screen with green ,yellow and red colors)

$cred=Get-Credential

$links=Get-Content c:\filepath.txt

foreach($WEBAPP in $links){
try { $response = Invoke-WebRequest $WEBAPP -Method get -Credential $cred

if($result -eq 200)
{

Write-Host $WEBAPP “up ” -ForegroundColor Green
}

}

catch {
$code=$_.Exception.Response.StatusCode.Value__
if ($code -gt 399 -and $code -le 499) {

Write-Host $WEBAPP “return $code” -foregroundColor yellow}

if ($code -gt 499 -and $code -le 599) {

Write-Host $WEBAPP “return $code” -foregroundColor red}

}

}