16

I need to integrate an existing powershell script to update it's status via a restful web service that returns json. I'm a bit new to powershell but I was able to find the System.Net.WebRequest object do something like the following.

$a = [System.Net.WebRequest]::Create("http://intranet/service/object/")
$a.Method = "GET"
$a.GetResponse()

which returns a json array of objects

[ {id:1}, {id:2}] // etc

I'm not sure where to go from here and how to parse this into a native datatype. I'd like to be able to post and delete as well.

Any pointers? And are there any json/rest libraries or command-lets?

reconbot
  • 5,138
  • 6
  • 45
  • 63

3 Answers3

28

What you want is PowerShell 3 and its Invoke-RestMethod, ConvertTo-Json, and ConvertFrom-Json cmdlets. Your code will end up looking like:

$stuff = invoke-RestMethod -Uri $url -Method Get;

and there shouldn't even be a need to invoke ConvertFrom-Json on the resulting $stuff => it's already in a usable non-string format.

As for POSTs|PUTs, simply use PowerShell hashes and arrays to structure your data and then call ConvertTo-Json on it before passing it to invoke-RestMethod or invoke-WebRequest:

invoke-WebRequest -Uri $url -ContentType application/json -Method Post -Body $objectConvertedToJson

See http://technet.microsoft.com/en-us/Library/hh849971.aspx for details.

Dave
  • 1,212
  • 12
  • 8
  • 1
    You are completely correct however powershell 3 is still pretty new and not deployed where I work. – reconbot Nov 12 '12 at 14:53
3

You could use DataContractJsonSerializer, which is a part of standard .Net library.

Victor Haydin
  • 3,518
  • 2
  • 26
  • 41
2

@Jaykul wrote a nice set of RESTful functions that are part of his Mindtouch dreamwiki script over here: http://poshcode.org/691

x0n
  • 51,312
  • 7
  • 89
  • 111