如何获取Powershell Invoke-Restmethod以返回http 500代码响应的主体?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (370)

Invoke-RestMethod调用仅返回下面非常无用的异常,并且不会允许收集主体内容(显示在fiddler跟踪结果中的JSON对象)。

invoke-restmethod -method Post -uri "https://api-stage.enviance.com/ver2/EqlService.svc/eql" -Body (ConvertTo-Json $eqlhash)  -Headers @{"Authorization"="Enviance $session"}

invoke-restmethod : The remote server returned an error: (500) Internal Server Error. At line:1 char:9...

Fiddler跟踪

HTTP/1.1 500 Internal Server Error Connection: close Date: Thu, 12 Sep 2013 17:35:00 GMT Server: Microsoft-IIS/6.0 X-Powered-By: ASP.NET X-AspNet-Version: 2.0.50727 EnvApi-Version: 2.0,2.0 EnvApi-Remaining-Calls: 994,994 EnvApi-Remaining-Interval: 2684,2684 Cache-Control: no-cache Pragma: no-cache Expires: -1 Content-Type: text/csv; charset=utf-8

{"errorNumber":0,"message":"Current user has no rights to retrieve data from table 'CustomFieldTemplate'"}

提问于
用户回答回答于

捕获该异常,然后才能从中提取响应。像这样使用:

$resp = try { Invoke-WebRequest ... } catch { $_.Exception.Response }
用户回答回答于

你需要一个额外的步骤来获得响应的实际正文,而不仅仅是标题。这是一个片段:

try {
        $result = Invoke-WebRequest ...
}
catch {
        $result = $_.Exception.Response.GetResponseStream()
        $reader = New-Object System.IO.StreamReader($result)
        $reader.BaseStream.Position = 0
        $reader.DiscardBufferedData()
        $responseBody = $reader.ReadToEnd();
}

扫码关注云+社区

领取腾讯云代金券