Skip to content

Instantly share code, notes, and snippets.

@craeckor
Last active November 25, 2024 14:35
Show Gist options
  • Select an option

  • Save craeckor/65edb8d7b8689bd90750dc99da7c3fdd to your computer and use it in GitHub Desktop.

Select an option

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.
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
}
}
}
@craeckor

Copy link
Copy Markdown
Author

Usage:

  1. Import with Import-Module .\Get-CurlDownload-Function.p1
  2. Use with Get-CurlDownload -URL "URL" -OutFile "DestinationPath"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment