简体   繁体   English

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

[英]How can I use Powershell to access a restful webservice?

I need to integrate an existing powershell script to update it's status via a restful web service that returns json. 我需要集成一个现有的powershell脚本,通过一个返回json的restful web服务来更新它的状态。 I'm a bit new to powershell but I was able to find the System.Net.WebRequest object do something like the following. 我对powershell有点新,但我能够找到System.Net.WebRequest对象,执行如下操作。

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

which returns a json array of objects 它返回一个json对象数组

[ {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? 有没有json / rest库或command-lets?

What you want is PowerShell 3 and its Invoke-RestMethod , ConvertTo-Json , and ConvertFrom-Json cmdlets . 你想要的是PowerShell 3及其Invoke-RestMethodConvertTo-JsonConvertFrom-Json cmdlet Your code will end up looking like: 您的代码最终将如下所示:

$stuff = invoke-RestMethod -Uri $url -Method Get; $ 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. 甚至不需要在结果$ stuff =>上调用ConvertFrom-Json它已经是一个可用的非字符串格式。

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: 对于POSTs | PUT,只需使用PowerShell哈希和数组来构造数据,然后在将其传递给invoke-RestMethod或invoke-WebRequest之前调用它上面的ConvertTo-Json

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

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

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM