Download.ps1 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. <#
  2. .SYNOPSIS
  3. Downloads a given uri and saves it to outputFile
  4. .DESCRIPTION
  5. Downloads a given uri and saves it to outputFile
  6. PARAMETER uri
  7. The uri to fetch
  8. .PARAMETER outputFile
  9. The outputh file path to save the uri
  10. #>
  11. param(
  12. [Parameter(Mandatory = $true)]
  13. $uri,
  14. [Parameter(Mandatory = $true)]
  15. $outputFile
  16. )
  17. [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
  18. $ProgressPreference = 'SilentlyContinue' # Don't display the console progress UI - it's a huge perf hit
  19. $maxRetries = 5
  20. $retries = 1
  21. while($true) {
  22. try {
  23. Write-Host "GET $uri"
  24. Invoke-WebRequest $uri -OutFile $outputFile
  25. break
  26. }
  27. catch {
  28. Write-Host "Failed to download '$uri'"
  29. $error = $_.Exception.Message
  30. }
  31. if (++$retries -le $maxRetries) {
  32. Write-Warning $error -ErrorAction Continue
  33. $delayInSeconds = [math]::Pow(2, $retries) - 1 # Exponential backoff
  34. Write-Host "Retrying. Waiting for $delayInSeconds seconds before next attempt ($retries of $maxRetries)."
  35. Start-Sleep -Seconds $delayInSeconds
  36. }
  37. else {
  38. Write-Error $error -ErrorAction Continue
  39. throw "Unable to download file in $maxRetries attempts."
  40. }
  41. }
  42. Write-Host "Download of '$uri' complete, saved to $outputFile..."