Is there a way to track download progress using a WebClient object in powershell?

I upload the file with a simple line:

$webclient = New-Object -TypeName System.Net.WebClient $webclient.DownloadFile("https://www.example.com/file", "C:/Local/Path/file") 

The problem is that I want to display a message to the user at boot time using a pop-up window or using a progress bar in the shell. Is it possible to create a popup that disappears when the download is complete, or a progress bar that tracks the download?

+6
source share
2 answers

To display a progress bar for downloading files, check out Jason Niver’s message:

Download files from the Internet to Power Shell (with progress)

Basically, you can create a function that still uses the functionality of the web client, but includes a way to capture status. You can then display the status for the user using the Write-Progress Power shell.

 function DownloadFile($url, $targetFile) { $uri = New-Object "System.Uri" "$url" $request = [System.Net.HttpWebRequest]::Create($uri) $request.set_Timeout(15000) #15 second timeout $response = $request.GetResponse() $totalLength = [System.Math]::Floor($response.get_ContentLength()/1024) $responseStream = $response.GetResponseStream() $targetStream = New-Object -TypeName System.IO.FileStream -ArgumentList $targetFile, Create $buffer = new-object byte[] 10KB $count = $responseStream.Read($buffer,0,$buffer.length) $downloadedBytes = $count while ($count -gt 0) { $targetStream.Write($buffer, 0, $count) $count = $responseStream.Read($buffer,0,$buffer.length) $downloadedBytes = $downloadedBytes + $count Write-Progress -activity "Downloading file '$($url.split('/') | Select -Last 1)'" -status "Downloaded ($([System.Math]::Floor($downloadedBytes/1024))K of $($totalLength)K): " -PercentComplete ((([System.Math]::Floor($downloadedBytes/1024)) / $totalLength) * 100) } Write-Progress -activity "Finished downloading file '$($url.split('/') | Select -Last 1)'" $targetStream.Flush() $targetStream.Close() $targetStream.Dispose() $responseStream.Dispose() } 

Then you just call the function:

 downloadFile "http://example.com/largefile.zip" "c:\temp\largefile.zip" 

In addition, here are some other Write-Progress examples.

Write progress

+6
source

In V2, you can simply use the BitsTransfer module, for example:

 Import-Module BitsTransfer Start-BitsTransfer https://www.example.com/file C:/Local/Path/file 
+4
source

All Articles