我需要集成一个现有的powershell脚本,以通过返回json的静态Web服务更新其状态.我对Powershell有点陌生,但是我发现System.Net.WebRequest对象可以执行以下操作.
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("intranet/service/object/") $a.Method = "GET" $a.GetResponse()返回对象的json数组
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.
有指针吗?还有任何json/rest库或Command-let吗?
Any pointers? And are there any json/rest libraries or command-lets?
推荐答案您需要的是PowerShell 3 及其 Invoke-RestMethod , ConvertTo-Json 和 ConvertFrom-Json cmdlet .您的代码最终看起来像:
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;
$stuff = invoke-RestMethod -Uri $url -Method Get;
,甚至不需要在生成的$ stuff =>上调用 ConvertFrom-Json ,它已经是可用的非字符串格式了.
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.
对于POST | PUT,只需使用PowerShell哈希和数组来构造数据,然后在将其传递给invoke-RestMethod或invoke-WebRequest之前调用 ConvertTo-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:
调用WebRequest -Uri $ url -ContentType application/json-方法发布-Body $ objectConvertedToJson
invoke-WebRequest -Uri $url -ContentType application/json -Method Post -Body $objectConvertedToJson
请参见 technet.microsoft/en-us/Library /hh849971.aspx 了解详情.
更多推荐
如何使用Powershell访问宁静的Web服务?
发布评论