Capture response on failed/401 Invoke-WebRequest


How do I capture the output when Invoke-WebRequest hits a 500, 401, 403, etc.? When the call is successful, it stores the result in the $Response variable, but if I hit a 401 it throws the error but doesn’t store the response.

The $Response variable remains null, however the endpoint is returning the 401 Unauthorized and headers, it’s just not being captured by PowerShell since it is treating it as an exception. Piping it through Fiddler confirms this.

Creating a request using [System.Net.WebRequest] has the same result when I execute $Response = $WebRequest.GetResponse().

Here’s my $PSVersionTable.


This is actually an open issue on the PowerShell project on GitHub, it might be resolved some day though.

For now, here is how we tend to work around that.

First, load this function into memory.

Then, wrap your WebRequests like this.

The cool thing about this approach is that it writes Globally Scoped Variables, and they’ll persist after your function exits. When you do encounter an error, just poke around inside $global:result or $global:responsebody for the full error.

This is a must-have when writing modules based on RPC or REST endpoints.

Credit for this technique goes to Steve Wahl.


Capture response on failed/401 Invoke-WebRequest by licensed under CC BY-SA | With most appropriate answer!

Leave a Reply