我正在编写一个powershell脚本,它需要发出一个web请求并检查响应的状态码。
我试着这样写:
$client = new-object system.net.webclient
$response = $client.DownloadData($url)
还有这个
$response = Invoke-WebRequest $url
但是每当网页有一个不是成功状态码的状态码时,PowerShell就会继续并抛出一个异常,而不是给我实际的响应对象。
如何在页面加载失败的情况下获取页面的状态码?
3条答案
按热度按时间00jrzges1#
试试这个:
这是一种失望,这抛出一个异常,但这就是它的方式。
根据评论更新
为了确保这样的错误仍然返回有效的响应,可以捕获
WebException
类型的异常并获取相关的Response
。由于异常的响应类型为
System.Net.HttpWebResponse
,而成功的Invoke-WebRequest
调用的响应类型为Microsoft.PowerShell.Commands.HtmlWebResponseObject
,为了从两种情况下返回兼容的类型,我们需要获取成功响应的BaseResponse
,它也是System.Net.HttpWebResponse
类型。这个新的响应类型的状态码是
[system.net.httpstatuscode]
类型的枚举,而不是简单的整数,因此您必须显式地将其转换为int,或者如上所述访问其Value__
属性以获取数字代码。bqjvbblv2#
自Powershell 7.0版本以来,
Invoke-WebRequest
具有-SkipHttpErrorCheck
开关参数。-SkipHttpErrorCheck
此参数使cmdlet忽略HTTP错误状态并继续处理响应。错误响应被写入管道,就像它们成功一样。
此参数是在PowerShell 7中引入的。
docspull request
s4n0splo3#
-SkipHttpErrorCheck
是PowerShell 7+的最佳解决方案,但如果您还不能使用它,那么这里有一个简单的替代方案,对于交互式命令行Poweshell会话非常有用。当您看到404响应的错误描述时,即
远程服务器返回错误:(404)页面没有找到
然后,您可以通过输入以下命令从命令行中看到“最后一个错误”:
或者
或者你想从“Response”对象中知道的任何其他信息。