Powershell 2.0 Download File [ Working · 2024 ]

<# .SYNOPSIS Download a file using PowerShell 2.0 with TLS 1.2 support. .DESCRIPTION This script uses System.Net.WebClient to download a file. It forces TLS 1.2 for modern HTTPS compatibility. .NOTES Author: Legacy IT Admin PowerShell Version: 2.0+ #> param( [Parameter(Mandatory=$true)] [string]$Url,

[Parameter(Mandatory=$true)] [string]$OutputPath,

[Parameter(Mandatory=$false)] [int]$TimeoutSeconds = 60, powershell 2.0 download file

try Out-Null $totalBytes = $client.ResponseHeaders["Content-Length"] if ($totalBytes -eq $null) Write-Warning "Server did not provide Content-Length. Cannot show progress." $client.DownloadFile($url, $outputPath) return $stream = $client.OpenRead($url) $fileStream = [System.IO.File]::OpenWrite($outputPath) $buffer = New-Object byte[] 8192 $downloaded = 0 $percentComplete = 0 while (($bytesRead = $stream.Read($buffer, 0, $buffer.Length)) -gt 0) $fileStream.Write($buffer, 0, $bytesRead) $downloaded += $bytesRead $newPercent = [Math]::Floor(($downloaded / $totalBytes) * 100) if ($newPercent -gt $percentComplete) $percentComplete = $newPercent Write-Progress -Activity "Downloading" -Status "$percentComplete% Complete" -PercentComplete $percentComplete Write-Progress -Activity "Downloading" -Completed Write-Host "Download complete: $outputPath"

Save as Download-File.ps1 and execute:

finally if ($stream) $stream.Close() if ($fileStream) $fileStream.Close() $client.Dispose()

catch Write-Error "[FAILED] Download error: $($ .Exception.Message)" if ($ .Exception.InnerException) Write-Error "Inner Exception: $($_.Exception.InnerException.Message)" param( [Parameter(Mandatory=$true)] [string]$Url

# The actual download $webClient.DownloadFile($Url, $OutputPath)