Last active
November 25, 2024 14:35
-
-
Save craeckor/65edb8d7b8689bd90750dc99da7c3fdd to your computer and use it in GitHub Desktop.
Downloads file from the internet to a specific path with proper error handling.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| function Get-CurlDownload { | |
| param( | |
| [Parameter(Position=0)] | |
| [string]$URL, | |
| [Parameter(Position=1)] | |
| [string]$OutFile | |
| ) | |
| if (-not $URL) { | |
| Write-Host "Please provide a URL" | |
| return | |
| } | |
| if (-not $OutFile) { | |
| Write-Host "Please provide an output file" | |
| return | |
| } | |
| $maxRetries = 10 | |
| $retryDelay = 10 | |
| $retryCount = 0 | |
| $FileAdded = $false | |
| while ($retryCount -lt $maxRetries -and -not $FileAdded) { | |
| curl.exe -k -s -L --connect-timeout 45 --retry 5 --retry-max-time 120 --retry-connrefused -o "$OutFile" -X GET "$URL" | |
| Start-Sleep -Seconds 3 | |
| if ($LASTEXITCODE -eq 0) { | |
| if (Test-Path -Path $OutFile) { | |
| $FileAdded = $true | |
| } else { | |
| Start-Sleep -Seconds $retryDelay | |
| $retryCount++ | |
| Remove-Item -Path $OutFile -Force | |
| Start-Sleep -Seconds 3 | |
| } | |
| } else { | |
| Start-Sleep -Seconds $retryDelay | |
| $retryCount++ | |
| Remove-Item -Path $OutFile -Force | |
| Start-Sleep -Seconds 3 | |
| } | |
| } | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage:
Import-Module .\Get-CurlDownload-Function.p1Get-CurlDownload -URL "URL" -OutFile "DestinationPath"