92

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

我试过写这个:

$client = new-object system.net.webclient

$response = $client.DownloadData($url)

还有这个:

$response = Invoke-WebRequest $url

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

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

4

3 回答 3

134

尝试这个:

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__
于 2013-10-01T17:42:02.037 回答
14

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

-SkipHttpErrorCheck

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

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

文档 拉取请求

于 2020-03-18T13:14:59.280 回答
4

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

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

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

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

$Error[0].Exception.Response.StatusCode

或者

$Error[0].Exception.Response.StatusDescription

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

于 2020-06-14T07:41:58.390 回答