为了实现更新机制,我目前必须获取存储在get服务器上的一些文件的大小。获取文件大小适用于我的脚本,但是每当我多次调用该函数时,它就会被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
发布于 2018-02-08 16:32:06
感谢@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
https://stackoverflow.com/questions/48683843
复制相似问题