powershell - 在powershell中获取HTTP请求并容忍500个服务器错误

标签 powershell http-request

在 Powershell v3.0 中,我想从 HTTP GET 返回响应代码,例如 200 OK500 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/

相关文章:

powershell - 将文件复制到远程桌面驱动器

azure - Microsoft Graph API 获取组事件

powershell - 在 PowerShell 脚本中测试管理员权限?

powershell - 为什么 PowerShell 中的 .NET 对象不使用当前目录?

linux - 在模块中找到命令,但无法加载模块

python - 将 header 与 Python 请求库的 get 方法一起使用

python - 使用 Python 请求的重定向错误太多

c# - 当 Http 请求发生实际下载时

http - 解析云 httpRequest strip 订阅 at_period_end 参数

python - 通过 Python Requests 模块发出 HTTP 请求不能通过 curl 的代理工作?为什么?