我正在使用如下简单的行下载文件:
$webclient = New-Object -TypeName System.Net.WebClient
$webclient.DownloadFile("https://www.example.com/file", "C:/Local/Path/file")
问题是我想在使用弹出窗口下载或使用shell中的进度条向用户显示消息。是否可以使下载完成时弹出框消失,或者监视下载进度的进度条?
答案 0 :(得分:12)
Downloading files from the internet in Power Shell (with progress)
基本上,您可以创建一个仍然使用Web客户端功能的功能,但包括一种捕获状态的方法。然后,您可以使用以下方式向用户显示状态 Write-Progress 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"
此外,还有一些其他Write-Progress示例。
<强> Write-Progress 强>
答案 1 :(得分:6)
在V2中你可以使用BitsTransfer模块,例如:
Import-Module BitsTransfer
Start-BitsTransfer https://www.example.com/file C:/Local/Path/file