Mario S
Mario S

Reputation: 85

Powershell getting stuck when doing webrequest

I currently have to get the size of some files stored on a webserver for the implementation of an update mechanism. Getting the file size works with my script, but whenever I call the function multiple times, it gets stuck at WebRequest.GetResponse(). When it gets stuck, I can't even stop the script with Ctrl-C. Does somebody know why this is happening or if there is a better way of doing this?

In the example I'm getting a test text file

Powershell script:

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) The output:

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

Upvotes: 1

Views: 1960

Answers (1)

Mario S
Mario S

Reputation: 85

Thanks @derloopkat for the solution. I forgot to Dispose the WebRequest object. So the code that's now working for me is:

    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

Upvotes: 1

Related Questions