I am using Powershell's Invoke-WebRequest
(this also applies to Invoke-RestMethod
) to make a call to an ElasticSearch cluster. This specific command often returns an error result (409 conflict
).
Powershell sees the error state, throws an error and does not pass anything useful through the pipeline, and it spews the body of the response onto the console:
However, a) even though it's got an error code, I don't really care that it's errored (only that it's returned), and b) I want to be able to access the body of that response so that I can actually inspect the data contained within.
Is there any way to have PowerShell suppress the error output (-ErrorAction
does not work) and pass something useful along the pipeline?
As a note, I actually want to invoke this with Invoke-RestMethod
but as it and Invoke-WebRequest
are essentially the same command, I've generalised this question to Invoke-WebRequest
Last year I wrote a script to diagnose common IIS setup problems, it's on GitHub, for it I needed to analyse the response from the server, even for non-200 results, especially for non-200 results, so
Invoke-WebRequest
didn't work.I removed some stuff and the essential code is below.
I use the .NET
System.Net.WebRequest
because even if aSystem.Net.WebException
is thrown, you can still access the response-stream with reponse headers and the body.