首页 > 代码库 > 并行执行
并行执行
$throttleLimit = 4
$SessionState = [system.management.automation.runspaces.initialsessionstate]::CreateDefault()
$Pool = [runspacefactory]::CreateRunspacePool(1, $throttleLimit, $SessionState, $Host)
$Pool.Open()
$id = 3
$ScriptBlock = {
#此处参数顺序要注意前后,AddArgument的第一个参数会被传递给$id,AddArgument的第二个参数会被传递给$x,与AddArgument的顺序无关,只与param的顺序有关
param($id,$x)
Start-Sleep -Seconds 1
"Done processing ID $id"
"hello, $x"
}
$threads = @()
$handles = for ($x = 1; $x -le 20; $x++) {
$powershell = [powershell]::Create().AddScript($ScriptBlock).AddArgument($id).addargument($x)
$powershell.RunspacePool = $Pool
$powershell.BeginInvoke()
$threads += $powershell
}
do {
$i = 0
$done = $true
foreach ($handle in $handles) {
if ($handle -ne $null) {
if ($handle.IsCompleted) {
$threads[$i].EndInvoke($handle)
$threads[$i].Dispose()
$handles[$i] = $null
} else {
$done = $false
}
}
$i++
}
if (-not $done) { Start-Sleep -Milliseconds 500 }
} until ($done)