3

So I'm calling a rest web service via powershell which responds with a 400 status code if you try to post data which has already been processed, along with the status code it also returns a JSON response in along the lines of:

{
    "statusCode": 400,
    "errorCode": "REQUEST_VALIDATION_ERROR",
    "message": "validation failed",
    "developerMessage": " MessageId-xxx already processed. No Need to process again."
}

So I try calling this with some powershell and receive the 400 status code and handle this using try/catch to get the exception, but there is no content in the response, I can get the response headers, status code, status message etc, but I cannot find a way to access the JSON response at all, here is the format of the powershell code I'm using:

$url = "https://example.com/webservice/status"
$cert = Get-ChildItem Cert:\CurrentUser\My\certthumbprintxxxxx
$headers = @{"tokenId" = "tokenxxxxx"}

$body = 
@"
{
...
 JSON data...
...
}
"@

try 
{
    $response = Invoke-WebRequest $url -Certificate $cert -Headers $headers -Method Post -Body $body
    }
catch
{
    $_.Exception.response
    }

When I send $_.Exception.response to Get-Member I can see that there is no content property. How can I access the message in the response using powershell?

steoleary
  • 8,968
  • 2
  • 33
  • 47

1 Answers1

7

You can access the content message from ErrorDetails Property via $_.ErrorDetails.Message. It returns a string.

As an alternative you can also directly read the stream from WebResponse class using $_.Exception.Response.GetResponseStream() (as described here, I had to put the stream to position 0 again as it seems to already have been read by powershell)

   $s = $_.Exception.Response.GetResponseStream()
   $s.Position = 0;
   $sr = New-Object System.IO.StreamReader($s)
   $err = $sr.ReadToEnd()
   $sr.Close()
   $s.Close()
Community
  • 1
  • 1
Fabian
  • 1,886
  • 14
  • 13
  • Brilliant, cheers, just a note is that in my case $_.ErrorDetails.Message was null, so I didn't get anything from there, directly reading the response stream worked a treat though. Thanks. – steoleary Sep 15 '15 at 13:29