gpt4 book ai didi

powershell - 有没有办法在powershell中使用WebClient对象来监控下载进度?

转载 作者:行者123 更新时间:2023-12-04 03:04:13 25 4
gpt4 key购买 nike

我正在使用这样的简单行下载文件:

$webclient = New-Object -TypeName System.Net.WebClient
$webclient.DownloadFile("https://www.example.com/file", "C:/Local/Path/file")

问题是我想在使用弹出窗口或使用 shell 中的进度条下载时向用户显示一条消息。是否可以制作一个下载完成时消失的弹出框,或者监控下载进度的进度条?

最佳答案

要显示下载文件的进度条,请查看 Jason Niver 的博客文章:
Downloading files from the internet in Power Shell (with progress)
基本上,您可以创建一个仍使用 Web 客户端功能但包括捕获状态的方法的函数。然后,您可以使用
写入进度 Power shell 功能。

function DownloadFile($url, $targetFile)

{

$uri = New-Object "System.Uri" "$url"

$request = [System.Net.HttpWebRequest]::Create($uri)

$request.set_Timeout(15000) #15 second timeout

$response = $request.GetResponse()

$totalLength = [System.Math]::Floor($response.get_ContentLength()/1024)

$responseStream = $response.GetResponseStream()

$targetStream = New-Object -TypeName System.IO.FileStream -ArgumentList $targetFile, Create

$buffer = new-object byte[] 10KB

$count = $responseStream.Read($buffer,0,$buffer.length)

$downloadedBytes = $count

while ($count -gt 0)

{

$targetStream.Write($buffer, 0, $count)

$count = $responseStream.Read($buffer,0,$buffer.length)

$downloadedBytes = $downloadedBytes + $count

Write-Progress -activity "Downloading file '$($url.split('/') | Select -Last 1)'" -status "Downloaded ($([System.Math]::Floor($downloadedBytes/1024))K of $($totalLength)K): " -PercentComplete ((([System.Math]::Floor($downloadedBytes/1024)) / $totalLength) * 100)

}

Write-Progress -activity "Finished downloading file '$($url.split('/') | Select -Last 1)'"

$targetStream.Flush()

$targetStream.Close()

$targetStream.Dispose()

$responseStream.Dispose()

}

然后你只需调用函数:
downloadFile "http://example.com/largefile.zip" "c:\temp\largefile.zip"

此外,这里还有一些来自 docs.microsoft 的用于 powshell 7 的其他写入进度示例。
Write-Progress

关于powershell - 有没有办法在powershell中使用WebClient对象来监控下载进度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21422364/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com