通过 Powershell 的 HTTP 状态代码

HTTP Status codes via Powershell

下面的代码在 C:\testurl.txt 中的前几个测试 URLs 中工作正常,然后它在处理来自 C 的第 4 个 URL 时永远挂断了:\testurl.txt ,不知道为什么挂了?

它已经可以正常工作长达 3 URL 秒,但在第 4 秒后卡住

CLS
$urllist = Get-Content "C:\testurl.txt" # URLs to test one in each line
foreach ($url in $urllist) {
    Write-Host $url

    $req = [System.Net.WebRequest]::Create($url)

    try {
        $res = $req.GetResponse()
    } catch [System.Net.WebException] {
        $res = $_.Exception.Response
    }

    $res.StatusCode
    #Print OK or whatever

    [int]$res.StatusCode
    #Print 200 or whatever
}

它在 3 URL 秒内工作正常,但在第 4 URL 秒挂起脚本,没有任何输出或错误消息。这是 c:\testurl.txt

的示例
http://www.google.com
http://www.google.com     
http://www.google.com
http://www.google.com
http://www.hotmail.com
http://www.gmail.com
http://www.yahoo.com
http://www.msn.com

请注意,每个 URL 都将换行,您会看到脚本将在(第 4 个)处停止,您也可以尝试使用自己的 URL,等等

then it hung up forever

否 - 它一直挂起,直到先前请求的基础 TCP 连接超时。

.NET CLR 将在内部汇集所有 WebRequest 调度,以便只有有限数量的外部请求会同时启动,并且只要您有一定数量的未关闭 WebResponse内存中的对象,您的请求将开始排队。

您可以通过关闭它们来避免这种情况(您应该这样做):

foreach ($url in $urllist) {
    Write-Host $url

    $req = [System.Net.WebRequest]::Create($url)

    try {
        $res = $req.GetResponse()
    } 
    catch [System.Net.WebException] {
        $res = $_.Exception.Response
    }
    finally {
        $res.StatusCode
        #Print OK or whatever

        [int]$res.StatusCode
        #Print 200 or whatever

        $res.Dispose()
        # close connection, dispose of response stream
    }
}