Powershell:捕捉 WebRequest Respose 与 Native Respose 不同

Powershell: Catching WebRequest Respose differs from Native Response

我在从 catch 块内的异常中获取与没有 catch 块时获取的相同数据时遇到了一点问题。

在没有 try/catch 块的情况下调用 Microsoft Defenders ATP API 会呈现以下错误消息:

Invoke-WebRequest : {"error":{"code":"ActiveRequestAlreadyExists","message":"Action is already in progress","target":"{security string redaction}"}}
At line:35 char:27
+ ... ardAction = Invoke-WebRequest -Uri $Offboarduri -Headers $Headers -Me ...
+                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-WebRequest], WebException
    + FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand

但是,当在 catch 块中时,无法捕获该消息中有用的任何附加信息(特别是 {code":"ActiveRequestAlreadyExists","message":"Action is already in进度"} 部分)

我已将以下内容放入我的捕获中以尝试调查反馈,但与该数据没有任何关联:

Write-Host "Exception Defaults"
$_.Exception | Select *
Write-Host "Exception Response Sub Text"
$_.Exception.Response | Select *

这些给我非常笼统的回复:

Exception Defaults
Status         : ProtocolError
Response       : System.Net.HttpWebResponse
Message        : The remote server returned an error: (400) Bad Request.
Data           : {}
InnerException : 
TargetSite     : System.Net.WebResponse GetResponse(System.Net.WebRequest)
StackTrace     :    at Microsoft.PowerShell.Commands.WebRequestPSCmdlet.GetResponse(WebRequest request)
                    at Microsoft.PowerShell.Commands.WebRequestPSCmdlet.ProcessRecord()
HelpLink       : 
Source         : Microsoft.PowerShell.Commands.Utility
HResult        : -2146233079

Exception Response Sub Text
IsMutuallyAuthenticated : False
Cookies                 : {}
Headers                 : {x-content-type-options, x-request-id, OData-Version, Strict-Transport-Security...}
SupportsHeaders         : True
ContentLength           : 137
ContentEncoding         : 
ContentType             : application/json; odata.metadata=minimal
CharacterSet            : 
Server                  : Microsoft-HTTPAPI/2.0
LastModified            : 04/03/2021 18:31:13
StatusCode              : BadRequest
StatusDescription       : Bad Request
ProtocolVersion         : 1.1
ResponseUri             : https://api.securitycenter.windows.com/api/machines/{security string redaction}/offboard
Method                  : POST
IsFromCache             : False

有谁知道我们可以捕获原始文本以使错误反馈比仅仅“错误请求”更具建设性的方法,以便更明显地表明请求是错误的,因为请求在前面它已经在进行中。

谢谢

阅读回复(可能已经阅读过):

# obtain stream
$stream = $_.Exception.Response.GetResponseStream()

try {
  # rewind stream cursor
  [void]$stream.Seek(0, 'Begin')

  # read entire response body
  $reader = [System.IO.StreamReader]::new($stream)
  $body = $reader.ReadToEnd()

  # return or parse/inspect $body here ...

}
finally {
  # clean up
  if($reader -is [System.IO.StreamReader]){
    $reader.Dispose()
  }
  $stream.Dispose()
}