Powershell Web 请求不会在 4xx/5xx 上引发异常 [英] Powershell web request without throwing exception on 4xx/5xx

查看:46
本文介绍了Powershell Web 请求不会在 4xx/5xx 上引发异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个 PowerShell 脚本,需要发出 Web 请求并检查响应的状态代码.

I'm writing a powershell script that needs to make a web request and inspect the status code of the response.

我试过写这个:

$client = new-object system.net.webclient

$response = $client.DownloadData($url)

还有这个:

$response = Invoke-WebRequest $url

但是只要网页的状态代码不是成功状态代码,PowerShell 就会继续抛出异常,而不是给我实际的响应对象.

but whenever the web page has a status code that's not a success status code, PowerShell goes ahead and throws an exception instead of giving me the actual response object.

如何在页面加载失败的情况下获取页面的状态代码?

How can I get the status code of the page even when it fails to load?

推荐答案

试试这个:

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__

这篇关于Powershell Web 请求不会在 4xx/5xx 上引发异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆