Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invoke-Restmethod: how do I get the return code?

Tags:

powershell

api

Is there a way to store the return code somewhere when calling Invoke-RestMethod in PowerShell?

My code looks like this:

$url = "http://www.dictionaryapi.com/api/v1/references/collegiate/xml/Adventure?key=MyKeyGoesHere"  $XMLReturned = Invoke-RestMethod -Uri $url -Method Get; 

I don't see anywhere in my $XMLReturned variable a return code of 200. Where can I find that return code?

like image 797
user952342 Avatar asked Jul 27 '16 20:07

user952342


People also ask

What does Invoke-RestMethod return?

The Invoke-RestMethod cmdlet sends HTTP and HTTPS requests to Representational State Transfer (REST) web services that return richly structured data. PowerShell formats the response based to the data type. For an RSS or ATOM feed, PowerShell returns the Item or Entry XML nodes.

What is the difference between invoke-RestMethod and invoke WebRequest?

Invoke-RestMethod - unlike Invoke-WebRequest - has deserialization built in: with a JSON response, it automatically parses the JSON text returned into a [pscustomobject] graph as if ConvertFrom-Json had been applied to it.


1 Answers

You have a few options. Option 1 is found here. It pulls the response code from the results found in the exception.

try {     Invoke-RestMethod ... your parameters here ...  } catch {     # Dig into the exception to get the Response details.     # Note that value__ is not a typo.     Write-Host "StatusCode:" $_.Exception.Response.StatusCode.value__      Write-Host "StatusDescription:" $_.Exception.Response.StatusDescription } 

Another option is to use the old invoke-webrequest cmdlet found here.

Code copied from there is:

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

Those are 2 ways of doing it which you can try.

like image 58
Ali Razeghi Avatar answered Sep 18 '22 14:09

Ali Razeghi