Question

I use Powershell version 3 and a I want to get as a Objects the data on an uri via Rest. I used the CmdLedt Invoke-RestMehtod:

 Invoke-RestMethod services.odata.org/OData/OData.svc/Advertisements?$format=json

My Output is:

id       : http://services.odata.org/OData/OData.svc/Advertisements(guid'f89dee73-a
       f9f-4cd4-b330-db93c25ff3c7')
category : category
link     : {link, link, link}
title    : 
updated  : 2013-10-29T09:06:33Z
author   : author
content  : content

But I want a Output, where ID, Name, Airdate is one Object like this(2 Objects):

Id                                      Name                                    Airdate
--                                      ----                                    -------
f89dee73-af9f-4cd4-b330-db93c25ff3c7    Old School Lemonade Store, Retro Style  2012-11-07T00:00:00
db2d2186-1c29-4d1e-88ef-a127f521b9c6    Early morning start, need coffee        2000-02-29T00:00:00

Can someone explain me how I could get with a CmdLedt via Rest a costum Object from a URI which returns a JSON?

Later I have to use this in C# code to get dynamic Objects from URI's and they are always different structured. Therfore I need this CmdLet, because it makes usually dynamic objects. In C# my Code so far:

 var args = new string[] { "http://services.odata.org/OData/OData.svc/?$format=json" };
 var command = string.Format("Invoke-RestMethod {0}", args[0]);

 var results = InvokeCommand.InvokeScript(command);
Was it helpful?

Solution

I've used Fiddler to compare the request from PowerShell and a request from a browser.

// PowerShell
GET /OData/OData.svc/Advertisements?=json HTTP/1.1
// Browser
GET /OData/OData.svc/Advertisements?$format=json HTTP/1.1

As you can see, the $format gets stripped from the URL and you will get an atom+xml response (just like requesting http://services.odata.org/OData/OData.svc/Advertisements, so without any URL parameters):

Content-Type: application/atom+xml;type=feed;charset=utf-8

In order to solve the problem, you need to escape the $ when you are using PowerShell.

Try this:

$obj = Invoke-RestMethod -uri "http://services.odata.org/OData/OData.svc/Advertisements?`$format=json"
$obj.value

The output (as you expected):

ID                                      Name                                    AirDate
--                                      ----                                    -------
f89dee73-af9f-4cd4-b330-db93c25ff3c7    Old School Lemonade Store, Retro Style  2012-11-07T00:00:00
db2d2186-1c29-4d1e-88ef-a127f521b9c6    Early morning start, need coffee        2000-02-29T00:00:00
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top