Powershell Web请求不会在4xx/5xx上抛出异常

ac1kyiln  于 2023-05-07  发布在  Shell
关注(0)|答案(3)|浏览(153)

我正在编写一个powershell脚本,它需要发出一个web请求并检查响应的状态码。
我试着这样写:

$client = new-object system.net.webclient

$response = $client.DownloadData($url)

还有这个

$response = Invoke-WebRequest $url

但是每当网页有一个不是成功状态码的状态码时,PowerShell就会继续并抛出一个异常,而不是给我实际的响应对象。
如何在页面加载失败的情况下获取页面的状态码?

00jrzges

00jrzges1#

试试这个:

try { $response = Invoke-WebRequest http://localhost/foo } catch {
      $_.Exception.Response.StatusCode.Value__}

这是一种失望,这抛出一个异常,但这就是它的方式。

根据评论更新

为了确保这样的错误仍然返回有效的响应,可以捕获WebException类型的异常并获取相关的Response
由于异常的响应类型为System.Net.HttpWebResponse,而成功的Invoke-WebRequest调用的响应类型为Microsoft.PowerShell.Commands.HtmlWebResponseObject,为了从两种情况下返回兼容的类型,我们需要获取成功响应的BaseResponse,它也是System.Net.HttpWebResponse类型。
这个新的响应类型的状态码是[system.net.httpstatuscode]类型的枚举,而不是简单的整数,因此您必须显式地将其转换为int,或者如上所述访问其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__
bqjvbblv

bqjvbblv2#

自Powershell 7.0版本以来,Invoke-WebRequest具有-SkipHttpErrorCheck开关参数。

-SkipHttpErrorCheck

此参数使cmdlet忽略HTTP错误状态并继续处理响应。错误响应被写入管道,就像它们成功一样。
此参数是在PowerShell 7中引入的。
docspull request

s4n0splo

s4n0splo3#

-SkipHttpErrorCheck是PowerShell 7+的最佳解决方案,但如果您还不能使用它,那么这里有一个简单的替代方案,对于交互式命令行Poweshell会话非常有用。
当您看到404响应的错误描述时,即
远程服务器返回错误:(404)页面没有找到
然后,您可以通过输入以下命令从命令行中看到“最后一个错误”:

$Error[0].Exception.Response.StatusCode

或者

$Error[0].Exception.Response.StatusDescription

或者你想从“Response”对象中知道的任何其他信息。

相关问题