如何从PowerShell脚本调用基于rest的API并处理Json答案?从PowerShell脚本调用REST API
38
A
回答
22
我创造了这个获取HTTP的功能,使HTTP请求
param([string]$url)
$req = [System.Net.WebRequest]::Create($url)
$req.Method ="GET"
$req.ContentLength = 0
$resp = $req.GetResponse()
$reader = new-object System.IO.StreamReader($resp.GetResponseStream())
$reader.ReadToEnd()
与以XML格式是很容易的,但是,如果要处理JSON你可能会需要一些NET库像最终的结果处理JSON.Net。
42
你想要的是PowerShell 3及其Invoke-RestMethod
,ConvertTo-Json
和ConvertFrom-Json
cmdlet。你的代码最终会看起来像:
$stuff = Invoke-RestMethod -Uri $url -Method Get;
而且甚至不应该是一个需要对所得到的$stuff
调用ConvertFrom-Json
=>它已经在使用非字符串格式。
查看http://technet.microsoft.com/en-us/Library/hh849971.aspx了解详情。
5
我们使用Powershell来查询仅处理Json样式数据的REST API。它起初很尴尬,但下面的代码是我们需要执行大多数操作的所有东西:
# Authentication
$webclient = New-Object System.Net.WebClient
$creds = New-Object System.Net.NetworkCredential("MyUsername","MyPassword");
$webclient.Credentials = $creds
# Data prep
$data = @{Name='Test';} | ConvertTo-Json
# GET
$webClient.DownloadString($url) | ConvertFrom-Json
# POST
$webClient.UploadString($url,'POST',$data)
# PUT
$webClient.UploadString($url,'PUT',$data)
相关问题
- 1. 从Ruby脚本中调用Elasticsearch Rest API
- 2. 从Java调用Powershell脚本
- 3. bash脚本输出到REST API调用
- 4. REST API调用或数据库脚本
- 5. Powershell调用Powershell脚本
- 6. 从另一个PowerShell脚本调用PowerShell脚本
- 7. 从非托管C++调用PowerShell脚本
- 8. 使用Powershell调用Rest API - CosmosDb
- 9. 从REST API中调用REST Api(Node.js)
- 10. 从另一个调用PowerShell脚本
- 11. “从脚本调用”Powershell工作流程
- 12. 从Azure Web作业调用Powershell脚本
- 13. 如何从套件脚本调用销售人员Rest API
- 14. 使用invoke-vmscript从powercli脚本调用PowerShell脚本?
- 15. Powershell脚本调用函数
- 16. 我的本地PowerShell脚本如何调用远程PowerShell脚本?
- 17. 脚本#调用REST服务
- 18. 从批处理脚本调用PowerShell脚本
- 19. 无法从另一个脚本调用PowerShell脚本
- 20. 如何从Windows PowerShell脚本调用Perl脚本
- 21. 无法从Powershell脚本调用脚本块
- 22. 从另一个脚本调用powershell脚本
- 23. 从PowerShell调用Vix API
- 24. 从REST API调用报告
- 25. 从api/app调用u-sql脚本的最佳方式(如rest api,wpf app)
- 26. 使用REST API和PowerShell
- 27. .NET API运行PowerShell脚本
- 28. 无法通过Powershell脚本获得API Rest响应
- 29. PowerShell脚本从CSV
- 30. 从Google Apps脚本调用Twitter API
这是否适用于SharePoint 2010? – craig 2015-01-07 15:53:30
您可能还需要提供凭证。在这种情况下,您将执行诸如$ stuff = Invoke-RestMethod -Uri $ url -Method Get -Credential“domain \ username”的命令。 – 2015-10-08 15:11:35
有没有办法传入Basic Auth的凭证? Jubblerbug所说的工作是展示一个弹出窗口询问密码,但我需要自动执行此 – 2017-04-13 16:47:09