Powershell v5.1 Invoke-RestMethod 错误解析正文

Powershell v5.1 Invoke-RestMethod Error Parsing Body

我是 Powershell 的初学者,正在尝试向 Microsoft Azure 发送 PUT 请求以创建 Application Insights 日志查询。我可以在 Postman 中使用它,但不能在 powershell 脚本中使用。这是我在 运行 脚本时遇到的错误:

Invoke-RestMethod : {"code":"解析值时遇到意外字符:S.Path '',第 0 行,位置 0。","message":"在解析时遇到意外字符解析值:S.Path '', line 0, position 0.","innererror":{"diagnosticcontext":"f2843c54-dad7-49b5-92ab-e1dadd40e145","time":"2020-07-24T19:59 :45.7979293Z"}}
在 C:\Users\thophan\source\Update-AiLogQueries.ps1:58 char:9
+调用-RestMethod -Method Put -Uri $uri -Header $header -Body ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~
+ 类别信息:InvalidOperation:(System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebException
+ FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand

从 Microsoft 文档来看,它似乎应该能够为正文输入哈希表,而且我很确定我的语法看起来与示例中的语法完全相同,所以我我不确定发生了什么。以下是我的脚本的摘录:

$scope = "shared"
$header = @{
    "Authorization" = "Bearer $token"
}
$uri = "https://management.azure.com/subscriptions/$subscriptionId/resourceGroups/$rgName/providers/microsoft.insights/components/$aiName/analyticsItems/item?api-version=2020-02-02-preview"
$difference = Compare-Object -ReferenceObject $localQueryList.value -DifferenceObject $response
if ($difference -ne $null)
{
    $difference.ForEach(
    {
        $body = @{
            Scope = $scope
            Type = "query"
            Name = $_.InputObject.Name
            Content = $_.InputObject.Content
        }

        Invoke-RestMethod -Method Put -Uri $uri -Header $header -Body $body
    })
}

更新:这是我按要求查看的文档。 https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/invoke-restmethod?view=powershell-5.1

API 要求正文是 JSON 字符串。您可以进行简单的转换(使用 ConvertTo-Json) in your Invoke-RestMethod 命令并相应地设置内容类型。

Invoke-RestMethod -Method Put -Uri $uri -Header $header -Body ($body | ConvertTo-Json) -ContentType 'application/json'