gpt4 book ai didi

Powershell Web 请求不会在 4xx/5xx 上引发异常

转载 作者:行者123 更新时间:2023-12-03 05:29:19 26 4
gpt4 key购买 nike

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

我尝试过这样写:

$client = new-object system.net.webclient

$response = $client.DownloadData($url)

还有这个:

$response = Invoke-WebRequest $url

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

即使页面加载失败,如何获取页面的状态代码?

最佳答案

试试这个:

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__

关于Powershell Web 请求不会在 4xx/5xx 上引发异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19122378/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com