并行执行

 

 1 $throttleLimit = 4
 2 $SessionState = [system.management.automation.runspaces.initialsessionstate]::CreateDefault()
 3 $Pool = [runspacefactory]::CreateRunspacePool(1, $throttleLimit, $SessionState, $Host)
 4 $Pool.Open()
 5 
 6 $id = 3
 7 $ScriptBlock = {
 8 #此处参数顺序要注意前后,AddArgument的第一个参数会被传递给$id,AddArgument的第二个参数会被传递给$x,与AddArgument的顺序无关,只与param的顺序有关
 9 param($id,$x)
10 #在此处定义需要执行的代码
11 Start-Sleep -Seconds 1
12 "Done processing ID $id"
13 "hello, $x"
14 }
15 
16 $threads = @()
17 #此处定义需要并行执行的进程总数($x)
18 $handles = for ($x = 1; $x -le 20; $x++) {
19 $powershell = [powershell]::Create().AddScript($ScriptBlock).AddArgument($id).addargument($x)
20 $powershell.RunspacePool = $Pool
21 $powershell.BeginInvoke()
22 $threads += $powershell
23 }
24 
25 do {
26 $i = 0
27 $done = $true
28 foreach ($handle in $handles) {
29 if ($handle -ne $null) {
30 if ($handle.IsCompleted) {
31 $threads[$i].EndInvoke($handle)
32 $threads[$i].Dispose()
33 $handles[$i] = $null
34 } else {
35 $done = $false
36 }
37 }
38 $i++
39 }
40 if (-not $done) { Start-Sleep -Milliseconds 500 }
41 } until ($done)

 

posted on 2014-05-28 09:40  momingliu11  阅读(653)  评论(0编辑  收藏  举报