答案 0 :(得分:31)
答案 1 :(得分:10)
答案 2 :(得分:4)
答案 3 :(得分:3)
答案 4 :(得分:0)
PowerShell runspaces是最接近线程并且性能比作业更好的东西。
这是一个非常基本的示例:
# the number of threads
$count = 10
# the pool will manage the parallel execution
$pool = [RunspaceFactory]::CreateRunspacePool(1, $count)
try {
$pool.Open()
# create and run the jobs to be run in parallel
$jobs = New-Object object[] $count
for ($i = 0; $i -lt $count; $i++) {
$ps = [PowerShell]::Create()
$ps.RunspacePool = $pool
# add the script block to run
[void]$ps.AddScript({
param($Index)
Write-Output "Index: $index"
})
# optional: add parameters
[void]$ps.AddParameter("Index", $i)
# start async execution
$jobs[$i] = [PSCustomObject]@{
PowerShell = $ps
AsyncResult = $ps.BeginInvoke()
}
}
foreach ($job in $jobs) {
try {
# wait for completion
[void]$job.AsyncResult.AsyncWaitHandle.WaitOne()
# get results
$job.PowerShell.EndInvoke($job.AsyncResult)
}
finally {
$job.PowerShell.Dispose()
}
}
}
finally {
$pool.Dispose()
}
除此之外,您还可以执行更高级的操作,例如限制池中并行运行空间的数量,或从当前会话中导入函数和变量等。
答案 5 :(得分:0)
answer现在非常简单。
Install-Module -Name ThreadJob -Confirm:$true
$j1= Start-ThreadJob `
-FilePath $YourThreadJob `
-ArgumentList @("A","B")
$j1|get-job
$j1|receive-job