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

rec*_*bot 16 rest powershell json

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

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

它返回一个json对象数组

[ {id:1}, {id:2}] // etc
Run Code Online (Sandbox Code Playgroud)

我不知道从这里去哪里以及如何将其解析为本机数据类型.我也希望能够发布和删除.

有什么指针吗?有没有json/rest库或command-lets?

Dav*_*ave 28

你想要的是PowerShell 3及其Invoke-RestMethod,ConvertTo-JsonConvertFrom-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.


Vic*_*din 3

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