Powershell handle Invoke-WebRequest 404 error

In some cases you may need to use Invoke-WebRequest of powershell as a correct result with status code of 404. A use case for this scenario would be a smoke test for a particular service or URL. In newer powershell versions you can use SkipHttpErrorCheck in order to stop powershell from failing the script.

The below example is a simple Web request that will fail on Powershell <7 with an exception if a 404 response is returned from the webpage.

$req = Invoke-WebRequest -Uri $url -Method GET

The parameter that you could use with Powershell 7++ and you would not have the powershell task failed would be.

$req = Invoke-WebRequest -Uri $url -Method GET -SkipHttpErrorCheck

In order to bypass this issue you could handle the exception on Powershell <7 and add your logic inside the catch block. For example

try {
    $resultApi = MakeWebRequest("http://localhost:1234/api/console") 
}
catch {
    if( $_.Exception.Response.StatusCode.Value__ -eq 404 ) 
    {
        Write-Host "API console Test 404 , proceeding ..."
    }
    else {
        Write-Host "False response..."
    }
}

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.