Hi there,
lately, I’ve been confronted with a problem where I simply couldn’t get meaningful error messages from failing runs of Invoke-Webrequest. In doing something like this:
1 2 3 4 5 6 |
Try { log "Creating new session token for $Url" $result = Invoke-WebRequest -uri $Url -Headers $headers -Method GET } Catch { $err = $_.Exception.Message |
$err would only ever contain the error code like “500 bla”, but not what the server actually returned as the error message. I was querying a REST API.
A colleague finally found the answer here.
What needs to be done is, to tell Powershell to read the stream. The exact difference I cannot tell, as this happens only for 5xx errors, as far as I can see.
1 2 3 4 5 6 |
Catch { $error = $_.Exception.Message $error2 = $_.Exception.Response.GetResponseStream() $stream = New-Object System.IO.StreamReader($error2) $response = $stream.ReadToEnd(); } |
$response will now contain the body of what the remote web service returned.
This is another good case that shows me, how easily one can get lost doing g**gle searches. I had searched for a solution also, but the sheer mass of results has overwhelmed me. Also, using only slightly different search terms always give totally different search results… Maybe I was using the wrong terms… Maybe I should have also read the documentation for Invoke-Webrequest more closely 🙂