更新时间:2023-11-12 13:19:10
试试这个:
try { $response = Invoke-WebRequest http://localhost/foo } catch {
$_.Exception.Response.StatusCode.Value__}
这引发异常有点令人沮丧,但事实就是如此.
It is kind of a bummer that this throws an exception but that's the way it is.
为确保此类错误仍然返回有效响应,您可以捕获那些 WebException
类型的异常并获取相关的 Response
.
To ensure that such errors still return a valid response, you can capture those exceptions of type WebException
and fetch the related Response
.
由于对异常的响应属于 System.Net.HttpWebResponse
类型,而来自成功的 Invoke-WebRequest
调用的响应属于 Microsoft 类型.PowerShell.Commands.HtmlWebResponseObject
,要从两种场景中返回兼容的类型,我们需要获取成功响应的 BaseResponse
,它也是 System.Net.HttpWebResponse
类型>.
Since the response on the exception is of type System.Net.HttpWebResponse
, whilst the response from a successful Invoke-WebRequest
call is of type Microsoft.PowerShell.Commands.HtmlWebResponseObject
, to return a compatible type from both scenarios we need to take the successful response's BaseResponse
, which is also of type System.Net.HttpWebResponse
.
这个新的响应类型的状态码是一个 [system.net.httpstatuscode]
类型的枚举,而不是一个简单的整数,所以你必须将它显式转换为 int,或者访问它的 Value__
属性如上所述以获取数字代码.
This new response type's status code an enum of type [system.net.httpstatuscode]
, rather than a simple integer, so you have to explicity convert it to int, or access it's Value__
property as described above to get the numeric code.
#ensure we get a response even if an error's returned
$response = try {
(Invoke-WebRequest -Uri 'localhost/foo' -ErrorAction Stop).BaseResponse
} catch [System.Net.WebException] {
Write-Verbose "An exception was caught: $($_.Exception.Message)"
$_.Exception.Response
}
#then convert the status code enum to int by doing this
$statusCodeInt = [int]$response.BaseResponse.StatusCode
#or this
$statusCodeInt = $response.BaseResponse.StatusCode.Value__