尝试这个:
try { $response = Invoke-WebRequest http://localhost/foo } catch {
$_.Exception.Response.StatusCode.Value__}
这会引发异常,这有点令人遗憾,但事实就是如此。
根据评论更新
为确保此类错误仍返回有效响应,您可以捕获这些异常类型WebException
并获取相关的Response
.
由于异常的响应是 type System.Net.HttpWebResponse
,而成功Invoke-WebRequest
调用的响应是 type Microsoft.PowerShell.Commands.HtmlWebResponseObject
,要从这两种情况返回兼容的类型,我们需要获取成功的响应BaseResponse
,它也是 type System.Net.HttpWebResponse
。
这个新的响应类型的状态码是一个枚举类型,而不是一个简单的整数,因此您必须将其显式转换为 int,或者如上所述[system.net.httpstatuscode]
访问它的属性以获取数字代码。Value__
#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__