【问题标题】:Powershell web request without throwing exception on 4xx/5xxPowershell Web 请求不会在 4xx/5xx 上引发异常
【发布时间】:2020-06-14 15:51:51
【问题描述】:

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

我试过写这个:

$client = new-object system.net.webclient

$response = $client.DownloadData($url)

还有这个:

$response = Invoke-WebRequest $url

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

页面加载失败如何获取状态码?

【问题讨论】:

标签: powershell


【解决方案1】:

试试这个:

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

这会引发异常,但事实就是如此。

按 cmets 更新

为确保此类错误仍然返回有效响应,您可以捕获WebException 类型的异常并获取相关的Response

由于异常的响应是 System.Net.HttpWebResponse 类型,而来自成功的 Invoke-WebRequest 调用的响应是 Microsoft.PowerShell.Commands.HtmlWebResponseObject 类型,要从两种情况下返回兼容的类型,我们需要采用成功响应的 @987654328 @,也是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__

【讨论】:

  • 谢谢,成功了。我没有意识到您可以只从 Exception 对象访问 Response 对象。
  • 是的,获取实际代码号有点棘手。 :-)
  • 一个稍微好一点的方法: $response = try { Invoke-WebRequest localhost/foo } catch { $_.Exception.Response } 这样你在这两种情况下都会在 $response 变量中得到一些东西。但请注意,失败返回 HtmlWebResponse,但成功返回 HtmlWebResponseObject。特别是,那些上的 StatusCode 是不同的类型(叹气..)
  • 但是在这种情况下如何获取响应内容呢?
  • 对 Rob 的建议进行了一些小的调整,以避免不同类型的问题:$response = try { (Invoke-WebRequest -Uri 'localhost/foo' -ErrorAction Stop).BaseRequest } catch [System.Net.WebException] { $_.Exception.Response }。 IE。获取BaseRequest 确保在成功和错误情况下我们都得到HttpWebReqponse。添加[System.Net.WebException] 可确保我们仅以这种方式捕获相关异常/不会意外扫除其他类型的问题。
【解决方案2】:

由于Powershell 7.0版Invoke-WebRequest-SkipHttpErrorCheck开关参数。

-SkipHttpErrorCheck

此参数使 cmdlet 忽略 HTTP 错误状态和 继续处理响应。错误响应被写入 就像他们成功一样。

此参数是在 PowerShell 7 中引入的。

docspull request

【讨论】:

  • 你太棒了!我的思绪开始发狂,试图找到一个解决方案,就是这个。
  • 也在Invoke-RestMethod
【解决方案3】:

-SkipHttpErrorCheck 是 PowerShell 7+ 的最佳解决方案,但如果您还不能使用它,那么这里有一个简单的替代方案,可用于交互式命令行 Poweshell 会话。

当您看到 404 响应的错误描述时,即

远程服务器返回错误:(404) Not Found.

然后您可以通过输入以下命令从命令行查看“最后一个错误”:

$Error[0].Exception.Response.StatusCode

或者

$Error[0].Exception.Response.StatusDescription

或者您想从“响应”对象中了解的任何其他信息。

【讨论】:

    猜你喜欢
    • 2011-07-06
    • 1970-01-01
    • 2018-05-25
    • 2023-03-14
    • 1970-01-01
    • 1970-01-01
    • 2022-01-01
    • 2011-11-16
    相关资源
    最近更新 更多