如何在PowerShell中无需缓冲区操作获取下载过程的实时已下载大小?
在PowerShell中无缓冲区获取实时下载大小的方法
可以实现,无需额外缓冲区操作就能追踪实时已下载大小。核心逻辑是:先通过HEAD请求拿到文件总大小,再利用.NET的WebClient对象的下载进度事件实时更新已下载量,全程无需将文件内容暂存到缓冲区中。
完整可运行脚本
# PowerShell下载Kubescape并显示实时进度 $fullurl = 'https://github.com/kubescape/kubescape/releases/download/v2.0.168/kubescape-windows-latest' $outputFile = Join-Path $env:TEMP "kubescape.exe" # 获取文件总大小 $totalSize = [long]((Invoke-WebRequest -Uri $fullurl -Method Head).Headers['Content-Length']) $downloadedSize = 0 # 创建WebClient并绑定进度变更事件 $webClient = New-Object System.Net.WebClient Register-ObjectEvent -InputObject $webClient -EventName DownloadProgressChanged -Action { $global:downloadedSize = $EventArgs.BytesReceived $percent = [math]::Floor((100 * $downloadedSize) / $Event.MessageData) Write-Host "`r下载进度: $percent% ($downloadedSize/$Event.MessageData 字节)" -NoNewline } -MessageData $totalSize | Out-Null # 开始异步下载 try { $webClient.DownloadFileTaskAsync($fullurl, $outputFile).Wait() Write-Host "`n下载完成!文件保存至: $outputFile" } finally { $webClient.Dispose() Unregister-Event -SourceIdentifier ($webClient.ID + "_DownloadProgressChanged") }
关键说明
- 无缓冲区实现:通过
WebClient的DownloadProgressChanged事件直接获取已下载字节数(BytesReceived),无需手动维护缓冲区存储下载内容。 - HEAD请求预获取总大小:先发送HEAD请求获取
Content-Length,用于计算下载百分比。 - 实时更新:利用事件回调实时刷新已下载大小和进度,避免低效轮询。
对示例脚本的补全说明
你提供的示例中$Downloaded_size += ?的位置,无需手动累加数值,通过绑定DownloadProgressChanged事件即可直接拿到实时已下载字节数,上述完整脚本就是该思路的落地实现。
内容的提问来源于stack exchange,提问作者Vicky Aryan
相关产品推荐
相关产品推荐

