Powershell - Http请求的无法解释的超时

时间:2012-06-11 23:50:56

标签: powershell httprequest powershell-v2.0

我有一个PowerShell脚本,可以监控少数几台服务器上的几个页面。它从每个中提供HTTP状态代码以确定服务器的运行状况。

这已经运行了好几个星期,但今天,在没有对脚本进行任何更改的情况下,我开始收到超时错误(“操作已经超时”)。端口80上的telnet到服务器让我立即通过,我可以通过我能想到的其他机制愉快地连接。

最后,我通过将超时时间从1000ms更改为2000ms来更新脚本,并且脚本立即再次运行。在我把它改回1000毫秒之后它仍然有效。

这是第二次以相同的分辨率发生这样的事情。发生了什么,我该如何避免呢?

2 个答案:

答案 0 :(得分:0)

这个脚本可能有所帮助,对你的情况可能有点过分。

function HTTP-Get() {
    param
    (
        [string] $target
    )

    try
    {
        $webRequest = [System.Net.WebRequest]::Create($target)
        $webRequest.Method = "GET"

        [System.Net.WebResponse] $resp = $webRequest.GetResponse();
        $rs = $resp.GetResponseStream();

        [System.IO.StreamReader] $sr = New-Object System.IO.StreamReader -argumentList $rs;
        [string] $results = $sr.ReadToEnd();
    }

    catch [System.Net.WebException] 
    {
        Write-Warning $_
        if ($_.response)
        {
            $_.response.Close();    
        }
    }

    finally
    {
        if ($sr)
        {
            $sr.close();
            $sr.dispose();
        }
        if ($resp)
        {
            $resp.close();
        }
    }

    return $results;
}

答案 1 :(得分:0)

As I mentioned in the comments: I had this issue with powershell and none of the .NET http tricks worked (httprequest, webclient). The site I used worked fine with postman and other http helpers.

It seemed like the issue is related to the .NET version, sp, etc. I changed my code to use COM instead of .NET and now it works fine.

......

$HTTPREQUEST_SETCREDENTIALS_FOR_SERVER = 0
$Http = new-object -com "WinHttp.WinHttpRequest.5.1"
$Http.open("GET", "http://....", $false)

$Http.SetCredentials($userName, $password, $HttpREQUEST_SETCREDENTIALS_FOR_SERVER) 

$Http.send()
$status = [int]$Http.Status
$responseText = $Http.responseText

.....

I hope it helps :)