我需要下載使用WebClient
文件中的PowerShell 2.0,我想展示下載進度,所以我也這樣說:PowerShell的:運行空間問題DownloadFileAsync
$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.
爲代碼在$downloadProgress
處理程序中,這是合乎邏輯的。但是,如何爲(可能)屬於ThreadPool
的線程提供Runspace
?
UPDATE: 注意既這個問題的答案是值得一讀的,如果我能我會接受這兩種。
謝謝,這是純粹的天才。比我的解決方案好得多。現在我會稍微等一下,看看有沒有人在接受之前回答Runspace部分(只是好奇它是如何處理的)。 – 2011-02-07 21:08:52
我會爲另一種選擇提供靈感:) – stej 2011-02-07 21:30:25