Dec
5
Written by:
Oisin Grehan
12/5/2007 12:01 AM
Here's another interesting use for my PowerShell Eventing Snap-In, where I'm simulating unix-style foreground/background tasks. In this case, the task is a large download using System.Net.WebClient. Just dot-source the script below and start a download using the Start-Download function, passing the url to the large file and the local path where to save your file (be sure to fully qualify the save path). The download will start immediately and show a progress bar with bytes remaining and a percentage, however you can hit Ctrl+C at any time and the download will continue in the background. You can get back to PowerShell tasks, and bring back up the progress bar by invoking Show-Progress at any time. Use Stop-Download to cancel the currently active download. Only one download can be active at a time, but this could easily be extended to support a pool of downloads (using multiple WebClient objects).
downloads.ps1 (1.85 KB)
-
-
- function Stop-Download {
- $wc.CancelAsync()
- }
-
- function Start-Download {
- param(
- [uri]$Url = $(throw "need Url."),
- [string]$Path = $(throw "Need save path.")
- )
-
-
- if (-not $global:wc) {
- $global:wc = New-Object System.Net.WebClient
- $var = get-variable wc
- Connect-EventListener -Variable $var `
- -EventName DownloadProgressChanged, DownloadFileCompleted
- }
-
- if ($wc.IsBusy) {
- Write-Warning "Currently busy: Please cancel current download or wait until it is completed."
- return
- }
-
- $wc.DownloadFileAsync($url, $path, $path)
- Write-Host "Download started. Ctrl+C to continue in background."
- Show-Progress
- }
-
- function Show-Progress {
- if (-not $wc.IsBusy) {
-
- get-event | Out-Null
- "No active download."
- return
- }
-
- Start-KeyHandler -CaptureCtrlC
-
- trap [exception] {
- Stop-KeyHandler
- Write-Warning "error"
- $_
- return
- }
-
- $exiting = $false
-
-
- while (-not $exiting) {
- $events = @(Get-Event -Wait)
- $event = $null;
-
-
- foreach ($event in $events) {
- if ($event.Name -eq "CtrlC") {
- break;
- }
- }
-
- switch ($event.Name) {
- "DownloadProgressChanged" {
- $r = $event.args.BytesReceived
- $t = $event.args.TotalBytesToReceive
- $activity = "Downloading $($event.args.userstate)"
- $p = [math]::Ceiling(([double]$r / $t) * 100)
- Write-Progress -Activity $activity -PercentComplete $p `
- -Status ("{0} of {1} byte(s)" -f $r,$t)
- }
- "DownloadFileCompleted" {
- Write-Progress -Activity DownloadComplete -Completed
- "Complete."
- $exiting = $true
- }
- "CtrlC" {
- "Switching to background downloading. Show-Progress to move to foreground."
- $exiting = $true
- }
- }
- }
- Stop-KeyHandler
- }
Tags: