I'm downloading a file using a simple line like this:
$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 while this is downloading using a pop up window, or using a progress bar in the shell. Is it possible to make a pop up box that disappears when the download completes, or a progress bar that monitors the progress of the download?
You can use the Write-Progress cmdlet to add a progress bar to any PowerShell script. Microsoft has provided a super simple script to show how this cmdlet works. The first line of the script sets up a loop. The loop starts with the $i variable set to 1 and each loop cycle increases the value of $i by 1 ($i++).
You can access Windows PowerShell Web Access by opening https://<server_name>/pswa in a browser window.
Downloading files from the internet in Power Shell (with progress)
Basically you can create a function that still uses the web client functionality but includes a way to capture the status. You can then display the status to the user using the Write-Progress Power shell functionality.
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 would just call the function:
downloadFile "http://example.com/largefile.zip" "c:\temp\largefile.zip"
Also, here are some other Write-Progress examples from docs.microsoft for powrshell 7.
Write-Progress
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With