如何使用Powershell访问宁静的Web服务? [英] How can I use Powershell to access a restful webservice?

查看:128
本文介绍了如何使用Powershell访问宁静的Web服务?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要集成一个现有的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("http://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

请参见 http://technet.microsoft.com/en-us/Library /hh849971.aspx 了解详情.

这篇关于如何使用Powershell访问宁静的Web服务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆