【问题标题】:Powershell v5.1 Invoke-RestMethod Error Parsing BodyPowershell v5.1 Invoke-RestMethod 错误解析正文
【发布时间】:2020-07-24 20:52:09
【问题描述】:

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

Invoke-RestMethod : {"code":"解析值时遇到意外字符:S。路径'',第 0 行,位置 0。","message":"解析值时遇到意外字符:S . 路径'',第 0 行,位置 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
+ Invoke-RestMethod -Method Put - Uri $uri -Header $header -Body ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: ( System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebException
+ FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand

通过查看 Microsoft 文档,它看起来应该能够为 body 接收一个哈希表,而且我很确定我的语法看起来与示例中的语法完全相同,所以我不知道发生了什么。以下是我的脚本的摘录:

$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

【问题讨论】:

  • 你能提供你关注的文档链接吗?
  • @AdminOfThings 我已根据您的要求更新了帖子以包含链接。
  • 道歉。我希望您关注的是 API 文档,而不是 PowerShell 命令。
  • @AdminOfThings 如果是这样,我没有遵循任何 API 文档。我使用 F12 Dev Tool 获得了 URI,然后我在 Postman 中使用 body 测试了 URI,效果很好。所以现在我只是试图将其转换为使用 Powershell 脚本。
  • $difference 的内容在这里是一个主要的未知数,因为您不仅要访问引用对象,还要访问该引用对象的属性。您知道 API 是否需要 PUT 中的 JSON 正文吗?如果是这样,很多 API 调用都会出错,因为它们应该包含 JSON 正文字符串 --> -Body ($body | convertTo-json) -ContentType 'application/json'

标签: powershell rest azure-powershell powershell-5.0 windows-scripting


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-02-04
    • 1970-01-01
    • 2020-11-06
    • 1970-01-01
    • 2016-06-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多