Skip to content

Instantly share code, notes, and snippets.

@dlwyatt
Last active March 30, 2022 11:59
Show Gist options
  • Save dlwyatt/2a893db5e022e60beced to your computer and use it in GitHub Desktop.
Save dlwyatt/2a893db5e022e60beced to your computer and use it in GitHub Desktop.
Write-Progress from WebClient
function Invoke-FileDownload
{
[CmdletBinding()]
param (
[Parameter(Mandatory)]
[uri] $Uri,
[Parameter(Mandatory)]
[string] $OutputFile
)
$webClient = New-Object System.Net.WebClient
$changed = Register-ObjectEvent -InputObject $webClient -EventName DownloadProgressChanged -Action {
Write-Progress -Activity "Downloading $Uri to $OutputFile" -PercentComplete $eventArgs.ProgressPercentage
}
$handle = $webClient.DownloadFileAsync($Uri, $PSCmdlet.GetUnresolvedProviderPathFromPSPath($OutputFile))
while ($webClient.IsBusy)
{
Start-Sleep -Milliseconds 10
}
Write-Progress -Activity "Downloading $Uri to $OutputFile" -Completed
Remove-Job $changed -Force
Get-EventSubscriber | Where SourceObject -eq $webClient | Unregister-Event -Force
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment