我目前必须获取存储在网络服务器上的一些文件的大小,以实现更新机制。获取文件大小适用于我的脚本,但每当我多次调用该函数时,它都会卡在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
答案 0 :(得分:1)
感谢@derloopkat提供解决方案。我忘了Dispose 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