Powershell:捕获WebRequest响应不同于本机响应



我遇到了一个小问题,从catch块内的异常中获得与没有捕获块时相同的数据。

在没有try/catch块的情况下调用Microsoft defender 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 progress&;}部分)

我在catch中放入了以下内容,试图对反馈进行调查,但没有任何内容与该数据相关:

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()
}

最新更新