How to get Powershell Invoke-Restmethod to return body of http 500 code response

The other answer does get you the response, but you need an additional step to get the actual body of the response, not just the headers. Here is a snippet:

try {
        $result = Invoke-WebRequest ...
}
catch {
        $result = $_.Exception.Response.GetResponseStream()
        $reader = New-Object System.IO.StreamReader($result)
        $reader.BaseStream.Position = 0
        $reader.DiscardBufferedData()
        $responseBody = $reader.ReadToEnd();
}

Although an old thread, here an answer to the problem with the cmdlets Invoke-WebRequest and Invoke-RestMethod.

This one has bothered me for quite some time. As all 4xx and 5xx responses are generating an exception, you have to catch that one and then you are able to extract the Response from there though. Use it like this:

$resp = try { Invoke-WebRequest ... } catch { $_.Exception.Response }

Now $resp always contains everything you like.