Powershell 在执行 webrequest 时卡住

Powershell getting stuck when doing webrequest

我目前必须获取存储在网络服务器上的一些文件的大小,以实现更新机制。获取文件大小适用于我的脚本,但每当我多次调用该函数时,它就会卡在 WebRequest.GetResponse()。当它卡住时,我什至无法使用 Ctrl-C 停止脚本。有人知道为什么会这样,或者是否有更好的方法?

在示例中,我得到了一个测试文本文件

Powershell 脚本:

function GetWebFileSize($fileurl) {
    try {
        Write-host "Getting size of file $fileurl"
        $clnt = [System.Net.WebRequest]::Create($fileurl)
        $resp = $clnt.GetResponse()
        $size = $resp.ContentLength;
        Write-host "Size of file is $size"
        return $size
    }
    catch {  
        Write-host "Failed getting file size of $fileurl"
        return 0
    }
}


[int]$counter = 0;

while (1 -eq 1) {
    $counter++;
    GetWebFileSize "https://raw.githubusercontent.com/mxstbr/markdown-test-file/master/README.md"
    Write "Passed $counter"
}

Output of powershell (picture) 输出:

C:\> .\WebFileSizeTest.ps1
Getting size of file https://raw.githubusercontent.com/mxstbr/markdown-test-file/master/README.md
Size of file is 1003
1003
Passed 1
Getting size of file https://raw.githubusercontent.com/mxstbr/markdown-test-file/master/README.md
Size of file is 1003
1003
Passed 2
Getting size of file https://raw.githubusercontent.com/mxstbr/markdown-test-file/master/README.md
Failed getting file size of https://raw.githubusercontent.com/mxstbr/markdown-test-file/master/README.md
0
Passed 3
Getting size of file https://raw.githubusercontent.com/mxstbr/markdown-test-file/master/README.md
Failed getting file size of https://raw.githubusercontent.com/mxstbr/markdown-test-file/master/README.md
0
Passed 4
Getting size of file https://raw.githubusercontent.com/mxstbr/markdown-test-file/master/README.md
Failed getting file size of https://raw.githubusercontent.com/mxstbr/markdown-test-file/master/README.md
0
Passed 5
Getting size of file https://raw.githubusercontent.com/mxstbr/markdown-test-file/master/README.md

感谢@derloopkat 提供的解决方案。我忘了处理 WebRequest 对象。所以现在对我有用的代码是:

    Write-host "Getting size of file $fileurl"
    $clnt = [System.Net.WebRequest]::Create($fileurl)
    $resp = $clnt.GetResponse()
    $size = $resp.ContentLength;
    $resp.Dispose();
    Write-host "Size of file is $size"
    return $size