![](/img/trans.png)
[英]convert curl command to invoke-WebRequest or Invoke-RestMethod
[英]Different results from Invoke-WebRequest and Invoke-RestMethod
我正在尝试调用 Azure Rest API 并获取 DevTestLabs 的计划。 我试图调用-RestMethod,但它并没有对“dailyRecurrence”键给值。 但是 Invoke-WebRequest 可以。
那是什么原因呢?
网址
$url = "https://management.azure.com/subscriptions/{subscriptionID}/resourceGroups/{resourseGroup}/providers/Microsoft.DevTestLab/labs/{LabName}/schedules/LabVmsShutdown?api-version=2018-10-15-preview"
带有 $expand 的 URL
$url = "https://management.azure.com/subscriptions/{subscriptionID}/resourceGroups/{resourseGroup}/providers/Microsoft.DevTestLab/labs/{LabName}/schedules/LabVmsShutdown?$expand=properties(dailyRecurrence)&api-version=2018-10-15-preview"
调用 Invoke-RestMethod
$output = Invoke-RestMethod -Uri $url -Method "GET" -ContentType "application/json" -Headers $authHeaders
properties : @{status=Enabled; taskType=LabVmsShutdownTask; dailyRecurrence=; timeZoneId=AUS Eastern Standard Time;
notificationSettings=; createdDate=26/03/2019 4:38:18 PM; provisioningState=Succeeded;
uniqueIdentifier=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX}
调用 Invoke-WebRequest
$output = Invoke-WebRequest -Uri $url -Method "GET" -Headers $authHeaders
Content : {"properties":{"status":"Enabled","taskType":"LabVmsShutdownTask","dailyRecurrence":{"time":"1900"}
,"timeZoneId":"AUS Eastern Standard Time","notificationSettings":{"status":"Disabled","timeInMinute
s":30},"createdDate":"2019-03-26T03:38:18.0726376+00:00","provisioningState":"Succeeded","uniqueIde
ntifier":"XXXXXXXXXXXXXXXXXXXXXXXXX"},"id":"/subscriptions/XXXXXXXXXXXXXXXXXXX/resourcegroups/XXXXXXXXXXXXX/providers/microsoft.devtestlab/labs/XXXXXXXX/schedules/labvmsshutdown","name":"LabVmsShutdown","type":"microsoft.devtestlab/labs/schedules","location":"australiasoutheast"}
问题:
只是显示问题,
尽管暴露了一个长期存在的错误,但在 PowerShell Core 7.2.0-rc.1 中仍然存在,即[pscustomobject]
实例错误地字符串[pscustomobject]
空字符串- 请参阅GitHub 问题 #6163 。
简而言之:
Invoke-RestMethod
输出,它只是似乎缺失-参见下一节。$output.properties.dailyRecurrence
来查看它,或者,为了更有帮助地可视化输出,使用它$output |
ConvertTo-Json
将其重新转换为(美化的)JSON。
-Depth
参数以完全表示深度大于 2 的对象图 - 请参阅此帖子。 Invoke-RestMethod
- 与Invoke-WebRequest
不同 -内置反序列化:使用 JSON 响应,它会自动将返回的 JSON 文本解析为[pscustomobject]
图形,就像对它应用了ConvertFrom-Json
一样。
您看到的是生成的对象图的默认格式,它并不真正适合可视化嵌套的[pscustomobject]
实例,这些实例由它们的.ToString()
值表示 - 因此 - 由于错误 - 可能看起来有没有价值,即使他们这样做。
相比之下,由于Invoke-WebRequest
的输出在其输出对象的.Content
属性中按.Content
报告 JSON 文本,因此问题并未出现在那里。
该错误的简单演示:
[pscustomobject] @{
nested =
[pscustomobject] @{
deep =
[pscustomobject] @{
deepest = 'down'
}
}
}
从 PowerShell Core 7.2.0-rc.1 开始,这会产生以下结果,错误地暗示.nested.deep
没有价值,即使它显然有:
nested
------
@{deep=}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.