EGr*_*EGr 9 powershell webclient powershell-2.0 webclient-download
我正在使用如下简单的行下载文件:
$webclient = New-Object -TypeName System.Net.WebClient
$webclient.DownloadFile("https://www.example.com/file", "C:/Local/Path/file")
Run Code Online (Sandbox Code Playgroud)
问题是我想在下载时使用弹出窗口或使用shell中的进度条向用户显示消息.下载完成时是否可以使弹出框消失,或者监视下载进度的进度条是否可以?
Sof*_*ter 12
在Power Shell中从Internet下载文件(带进度)
基本上,您可以创建一个仍然使用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()
}
Run Code Online (Sandbox Code Playgroud)
然后你只需要调用该函数:
downloadFile "http://example.com/largefile.zip" "c:\temp\largefile.zip"
Run Code Online (Sandbox Code Playgroud)
此外,还有一些其他Write-Progress示例.
在V2中你可以使用BitsTransfer模块,例如:
Import-Module BitsTransfer
Start-BitsTransfer https://www.example.com/file C:/Local/Path/file
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
12445 次 |
最近记录: |