更新时间:2023-01-03 18:24:41
根据 Invoke-RestMethod 文档,cmdlet 可以根据它接收到的内容返回不同的类型.将 cmdlet 输出分配给变量 ($resp = Invoke-RestMethod (...)
),然后检查类型是否为 HtmlWebResponseObject
($resp.gettype()
).然后,您将拥有许多属性供您使用,例如 BaseResponse、Content 和 StatusCode.
According to Invoke-RestMethod documentation, cmdlet can return different types depending on the content it receives. Assing cmdlet output to a variable ($resp = Invoke-RestMethod (...)
) and then check if the type is HtmlWebResponseObject
($resp.gettype()
). Then you'll have many properties at your disposal, like BaseResponse, Content and StatusCode.
如果 $resp
是其他类型(字符串、psobject,在这种情况下很可能是 null),似乎错误消息 远程服务器返回错误:(400) Bad Request
是响应主体,仅从 html 中剥离(我在我的一些方法上测试过),甚至可能被截断.如果要提取它,请使用通用参数运行 cmdlet 以存储错误消息:Invoke-RestMethod (...) -ErrorVariable RespErr
,您将在 $RespErr
变量.
If $resp
is some other type (string, psobject and most probably null in this case), it seems that error message The remote server returned an error: (400) Bad Request
is the response body, only stripped from html (I tested this on some of my methods), maybe even truncated . If you want to extract it, run the cmdlet using common parameter to store the error message: Invoke-RestMethod (...) -ErrorVariable RespErr
and you'll have it in $RespErr
variable.
好的,我明白了,这很明显:).Invoke-RestMethod 抛出一个错误,所以让我们抓住它:
Ok, I got it and it was pretty obvious :). Invoke-RestMethod throws an error, so lets just catch it:
try{$restp=Invoke-RestMethod (...)} catch {$err=$_.Exception}
$err | Get-Member -MemberType Property
TypeName: System.Net.WebException
Name MemberType Definition
---- ---------- ----------
Message Property string Message {get;}
Response Property System.Net.WebResponse Response {get;}
Status Property System.Net.WebExceptionStatus Status {get;}
这里有您所需要的一切,尤其是在 WebResponse 对象中.我列出了 3 个引人注目的属性,还有更多.此外,如果您存储 $_
而不是 $_.Exception
,PowerShell 可能已经为您提取了一些属性,但我认为没有比 .Exception.Response
.
Here's all you need, especially in WebResponse object.
I listed 3 properties that catch the eye, there's more. Also if you store $_
instead of $_.Exception
there could be some properties PowerShell already extracted for you, but I don't expect nothing more meaningful than in .Exception.Response
.