暂停脚本,直到powershell中的条件为真

时间:2017-02-28 23:03:25

标签: powershell

$vcconnect有50台机器,我需要在所有50台机器上运行这个工作,但是当我运行它时,它会崩溃shell。

我想在某个时间点将并行执行限制为10.

我尝试了一段时间,但我错过了一些东西,因为它同时在所有50个上执行并且使我的外壳崩溃。

foreach($vci in $vcconnect){ 
    [array]$jobstart += Start-Job -Name top2 -ArgumentList @($vci, $cred, $from,  $to) -ScriptBlock $importcode
}

1 个答案:

答案 0 :(得分:1)

如果要并行运行脚本,并控制并发运行的实例的最大数量,请使用RunspacePool

# Create a RunspacePool, of maximum 10 concurrently running runspaces
$RSPool = [runspacefactory]::CreateRunspacePool(1,10)
$RSPool.Open()

# Start a new "job" for each server
$Jobs = foreach($vci in $vconnect){
    $PS = [PowerShell]::Create().AddScript($importcode)
    $PS.RunspacePool = $RSPool
    $vci, $cred, $from,  $to |ForEach-Object {
        [void]$PS.AddArgument($_)
    }
    New-Object psobject -Property @{
        Shell = $PS
        ComputerName = $vci
        ResultHandle = $PS.BeginInvoke()
    }
}

# Wait for the "jobs" to finish
do{
    Start-Sleep -Milliseconds 500
} while ($Jobs |Where-Object IsCompleted -eq $false)

# Collect results, suppress (but warn on) errors
$Results = foreach($Job in $Jobs){
    $Job.Shell.EndInvoke($Job.ResultHandle)
    if($Job.Shell.HadErrors){
        Write-Warning "$($Job.ComputerName) had $($Job.Shell.Streams.Error.Count) errors:"
        $Job.Shell.Streams.Error |Write-Warning
    }
}