2011-02-07 81 views
11

我需要下载使用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: 注意这个问题的答案是值得一读的,如果我能我会接受这两种。

回答

12

谢谢stej的点头。

安德烈,PowerShell有它自己的线程池和各服务线程保持一个threadstatic指针运行空间(该System.Management.Automation.Runspaces.Runspace.DefaultRunspace静态成员暴露了这一点 - 将是你的回调空裁判。 )最终这意味着很难 - 尤其是在脚本中 - 使用您自己的线程池(如由.NET提供的异步方法)来执行脚本块。

的PowerShell 2.0

无论如何,没有必要玩这个作为的PowerShell V2已经为三项赛的全力支持:

$client = New-Object System.Net.WebClient 
$url = [uri]"http://download.microsoft.com/download/6/2/F/" + 
    "62F70029-A592-4158-BB51-E102812CBD4F/IE9-Windows7-x64-enu.exe" 

try { 

    Register-ObjectEvent $client DownloadProgressChanged -action {  

     Write-Progress -Activity "Downloading" -Status ` 
      ("{0} of {1}" -f $eventargs.BytesReceived, $eventargs.TotalBytesToReceive) ` 
      -PercentComplete $eventargs.ProgressPercentage  
    } 

    Register-ObjectEvent $client DownloadFileCompleted -SourceIdentifier Finished 

    $file = "c:\temp\ie9-beta.exe" 
    $client.DownloadFileAsync($url, $file) 

    # optionally wait, but you can break out and it will still write progress 
    Wait-Event -SourceIdentifier Finished 

} finally { 
    $client.dispose() 
} 

的PowerShell 1.0

如果您'重新粘在v1上(这个问题并不是专门针对你的,因为你在问题中提到了v2),你可以使用我的powershell 1.0事件管理单元http://pseventing.codeplex.com/

异步回调

在.NET另一个棘手的面积是异步回调。powershell的v1或v2中没有任何东西可以帮助你,但是你可以用一些简单的管道将异步回调转换为事件,然后使用常规事件处理该事件。我在http://poshcode.org/1382

希望这有助于发布这个(新ScriptBlockCallback)的脚本,

-Oisin

6

我看到您使用异步调用,以便您可以显示进度。然后你可以使用BitsTransfer模块。它显示了进步默认:

Import-Module BitsTransfer 
Start-BitsTransfer -Source $url -dest d:\temp\yourfile.zip 

如果你想传输文件在后台,你可以使用这样的事情:

Import-Module BitsTransfer 

$timer = New-Object Timers.Timer 
$timer.Interval = 300 
Register-ObjectEvent -InputObject $timer -EventName Elapsed -Action { 
    if ($transfer.JobState -ne 'Transferring') { 
     $timer.Enabled = 0; 
     Write-Progress -Completed -Activity Downloading -Status done 
     return 
    } 
    $progress = [int](100* $transfer.BytesTransferred/$transfer.BytesTotal) 
    Write-Progress -Activity Downloading -Status "$progress% done" -PercentComplete $progress 
} -sourceId mytransfer 
$transfer = Start-BitsTransfer -Source $url -dest d:\temp\yourfile.zip -async 
$timer.Enabled = 1 

# after that 
Unregister-Event -SourceIdentifier mytransfer 
$timer.Dispose() 

的关键参数是-async。它开始在后台传输。我还没有发现任何由传输触发的事件,所以我每秒查询一次作业,通过Timers.Timer对象报告状态。

但是,使用此解决方案时,需要取消注册事件并处理计时器。前段时间,我在作为-Action(它可能在if分支中)传递的scriptblock中发生了取消注册的问题,因此我使用单独的命令取消了注册事件。


我觉得@oising(x0n)在他的博客上有一些解决方案。他会很有希望地告诉你,那将是你的问题的答案。

+0

谢谢,这是纯粹的天才。比我的解决方案好得多。现在我会稍微等一下,看看有没有人在接受之前回答Runspace部分(只是好奇它是如何处理的)。 – 2011-02-07 21:08:52

+0

我会为另一种选择提供灵感:) – stej 2011-02-07 21:30:25