download-module.psm1 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. # Powershell supports only TLS 1.0 by default. Add support up to TLS 1.2
  2. [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.SecurityProtocolType]'Tls,Tls11,Tls12'
  3. Function DownloadFileWithProgress {
  4. # Code for this function borrowed from http://poshcode.org/2461
  5. # Thanks Crazy Dave
  6. # This function downloads the passed file and shows a progress bar
  7. # It receives two parameters:
  8. # $url - the file source
  9. # $localfile - the file destination on the local machine
  10. param(
  11. [Parameter(Mandatory=$true)]
  12. [String] $url,
  13. [Parameter(Mandatory=$false)]
  14. [String] $localFile = (Join-Path $pwd.Path $url.SubString($url.LastIndexOf('/')))
  15. )
  16. begin {
  17. Write-Host -ForegroundColor DarkGreen " download-module.DownloadFileWithProgress $url"
  18. $client = New-Object System.Net.WebClient
  19. $Global:downloadComplete = $false
  20. $eventDataComplete = Register-ObjectEvent $client DownloadFileCompleted `
  21. -SourceIdentifier WebClient.DownloadFileComplete `
  22. -Action {$Global:downloadComplete = $true}
  23. $eventDataProgress = Register-ObjectEvent $client DownloadProgressChanged `
  24. -SourceIdentifier WebClient.DownloadProgressChanged `
  25. -Action { $Global:DPCEventArgs = $EventArgs }
  26. }
  27. process {
  28. Write-Progress -Activity 'Downloading file' -Status $url
  29. $client.DownloadFileAsync($url, $localFile)
  30. while (!($Global:downloadComplete)) {
  31. $pc = $Global:DPCEventArgs.ProgressPercentage
  32. if ($pc -ne $null) {
  33. Write-Progress -Activity 'Downloading file' -Status $url -PercentComplete $pc
  34. }
  35. }
  36. Write-Progress -Activity 'Downloading file' -Status $url -Complete
  37. }
  38. end {
  39. Unregister-Event -SourceIdentifier WebClient.DownloadProgressChanged
  40. Unregister-Event -SourceIdentifier WebClient.DownloadFileComplete
  41. $client.Dispose()
  42. $Global:downloadComplete = $null
  43. $Global:DPCEventArgs = $null
  44. Remove-Variable client
  45. Remove-Variable eventDataComplete
  46. Remove-Variable eventDataProgress
  47. [GC]::Collect()
  48. # 2016-07-06 mkr Errorchecking added. nice-to-have: integration into the above code.
  49. If (!((Test-Path "$localfile") -and ((Get-Item "$localfile").length -gt 0kb))) {
  50. Write-Error "Exiting because download missing or zero-length: $localfile"
  51. exit 2
  52. }
  53. }
  54. }