在 Powershell v3.0 中,我想从 HTTP GET 返回响应代码,例如 200 OK
或 500 Internal Server Error
. (这是一个 hack-deploy 对已部署站点进行快速预热并查看它是否有效,一种小型验收测试。状态代码确实是我想要的。)
违背我的意愿,HttpWebRequest.GetResponse
收到 500 Internal Server Error
时抛出错误.这很烦人,因为在我的用例中这对我来说并不是真正的错误。无论如何,我认为我可以捕获异常并仍然剥离底层响应代码,但是我遇到了麻烦。
这是一些几乎可以工作的代码:
function WebResponseStatusCode (
[Parameter(Mandatory=$true)][string] $url
) {
$req = [system.Net.HttpWebRequest]::Create($url)
try {
$res = $req.GetResponse();
$statuscode = $res.statuscode;
}
catch [System.Net.WebException] {
#the outer error is a System.Management.Automation.ErrorRecord
Write-Host "error!"
return = $_.Response.statuscode; #nope
}
finally {
if (!($res -eq $null)) {
$res.Close();
}
}
return $statuscode;
}
问题当然是
$_
没有 Response
属性(property)。 $_.InnerException
也不行,即使在转换时:return [System.Net.WebException]($_.InnerException)
我玩过
$_ | Get-Member
并探索它的所有属性。我以为$_.TargetObject
有一些 promise ,但似乎没有。( 更新 ) 我也想我尝试了
$_.Exception.Response
的变体虽然可能弄错了。仅获取响应代码似乎是一件很简单的事情。
最佳答案
这是一个示例,尽管它做了一些更多的事情来允许您测试重定向以及预期的异常。
function GetWebSiteStatusCode {
param (
[string] $testUri,
$maximumRedirection = 5
)
$request = $null
try {
$request = Invoke-WebRequest -Uri $testUri -MaximumRedirection $maximumRedirection -ErrorAction SilentlyContinue
}
catch [System.Net.WebException] {
$request = $_.Exception.Response
}
catch {
Write-Error $_.Exception
return $null
}
$request.StatusCode
}
GetWebSiteStatusCode -testUri "https://www.google.com/"
GetWebSiteStatusCode -testUri "https://www.google.com/foobar"
GetWebSiteStatusCode -testUri "http://google.com/" -maximumRedirection 0
GetWebSiteStatusCode -testUri "https://accounts.google.com" -maximumRedirection 0
GetWebSiteStatusCode -testUri "https://www.googleapis.com/coordinate/v1/teams/1/custom_fields?fields=1111&key="
GetWebSiteStatusCode -testUri "https://www.googleapis.com/shopping/search/v1/test/products/sasdf/asdf/asdf?key="
#Next test would be for an expected 500 page.
#GetWebSiteStatusCode -testUri "https://www.somesite.com/someurlthatreturns500"
关于powershell - 在powershell中获取HTTP请求并容忍500个服务器错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22696981/