簡體   English   中英

Invoke-WebRequest 和 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM