【发布时间】:2011-02-07 20:16:13
【问题描述】:
我需要在 PowerShell 2.0 中使用 WebClient 下载文件,并且我想显示下载进度,所以我这样做了:
$activity = "Downloading"
$client = New-Object System.Net.WebClient
$urlAsUri = New-Object System.Uri($url)
$event = New-Object System.Threading.ManualResetEvent($false)
$downloadProgress = [System.Net.DownloadProgressChangedEventHandler] {
$progress = [int]((100.0 * $_.BytesReceived) / $_.TotalBytesToReceive)
Write-Progress -Activity $activity -Status "${progress}% done" -PercentComplete $progress
}
$downloadComplete = [System.ComponentModel.AsyncCompletedEventHandler] {
Write-Progress -Activity $activity -Completed
$event.Set()
}
$client.add_DownloadFileCompleted($downloadComplete)
$client.add_DownloadProgressChanged($downloadProgress)
Write-Progress -Activity $activity -Status "0% done" -PercentComplete 0
$client.DownloadFileAsync($urlAsUri, $file)
$event.WaitOne()
There is no Runspace available to run scripts in this thread. 处理程序中的代码出现错误 There is no Runspace available to run scripts in this thread.,这是合乎逻辑的。但是,如何为(可能)属于ThreadPool 的线程提供Runspace?
更新: 请注意,这个问题的两个答案都值得一读,如果可以的话,我会同时接受。
【问题讨论】: