salt/pkg/windows/modules/download-module.psm1
2016-02-12 21:00:30 -07:00

52 lines
1.9 KiB
PowerShell

Function DownloadFileWithProgress {
# Code for this function borrowed from http://poshcode.org/2461
# Thanks Crazy Dave
# This function downloads the passed file and shows a progress bar
# It receives two parameters:
# $url - the file source
# $localfile - the file destination on the local machine
param(
[Parameter(Mandatory=$true)]
[String] $url,
[Parameter(Mandatory=$false)]
[String] $localFile = (Join-Path $pwd.Path $url.SubString($url.LastIndexOf('/')))
)
begin {
$client = New-Object System.Net.WebClient
$Global:downloadComplete = $false
$eventDataComplete = Register-ObjectEvent $client DownloadFileCompleted `
-SourceIdentifier WebClient.DownloadFileComplete `
-Action {$Global:downloadComplete = $true}
$eventDataProgress = Register-ObjectEvent $client DownloadProgressChanged `
-SourceIdentifier WebClient.DownloadProgressChanged `
-Action { $Global:DPCEventArgs = $EventArgs }
}
process {
Write-Progress -Activity 'Downloading file' -Status $url
$client.DownloadFileAsync($url, $localFile)
while (!($Global:downloadComplete)) {
$pc = $Global:DPCEventArgs.ProgressPercentage
if ($pc -ne $null) {
Write-Progress -Activity 'Downloading file' -Status $url -PercentComplete $pc
}
}
Write-Progress -Activity 'Downloading file' -Status $url -Complete
}
end {
Unregister-Event -SourceIdentifier WebClient.DownloadProgressChanged
Unregister-Event -SourceIdentifier WebClient.DownloadFileComplete
$client.Dispose()
$Global:downloadComplete = $null
$Global:DPCEventArgs = $null
Remove-Variable client
Remove-Variable eventDataComplete
Remove-Variable eventDataProgress
[GC]::Collect()
}
}