首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Powershell在执行webrequest时卡住

Powershell在执行webrequest时卡住
EN

Stack Overflow用户
提问于 2018-02-08 18:57:51
回答 1查看 955关注 0票数 1

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

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

Powershell脚本:

代码语言:javascript
运行
复制
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)操作:

代码语言:javascript
运行
复制
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
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-02-09 00:32:06

感谢@derloopkat的解决方案。我忘了销毁WebRequest对象。所以现在为我工作的代码是:

代码语言:javascript
运行
复制
    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
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/48683843

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档