如何使用Powershell访问安静的Web服务?

时间:2011-01-04 20:29:20

标签: json rest powershell

我需要集成一个现有的PowerShell脚本,通过一个返回json的restful web服务来更新它的状态。我对powershell有点新,但我能够找到System.Net.WebRequest对象,执行以下操作。

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

返回一个json对象数组

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

我不确定从何处开始以及如何将其解析为本机数据类型。我也希望能够发布和删除。

任何指针?是否有任何json / rest库或command-lets?

3 个答案:

答案 0 :(得分:28)

你想要的是PowerShell 3 及其 Invoke-RestMethod ConvertTo-Json ConvertFrom-Json cmdlet 。您的代码最终将如下所示:

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

并且甚至不需要在结果$ stuff =>上调用 ConvertFrom-Json 。它已经是一个可用的非字符串格式。

对于POSTs | PUT,只需使用PowerShell哈希和数组来构建数据,然后在将其传递给invoke-RestMethod或invoke-WebRequest之前调用 ConvertTo-Json

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

有关详细信息,请参阅http://technet.microsoft.com/en-us/Library/hh849971.aspx

答案 1 :(得分:3)

您可以使用DataContractJsonSerializer,它是标准.Net库的一部分。

答案 2 :(得分:2)

@Jaykul在这里编写了一组很好的RESTful函数,这些函数是他的Mindtouch dreamwiki脚本的一部分:http://poshcode.org/691