等到所有线程完成后再运行下一个任务

时间:2017-07-18 16:08:04

标签: multithreading powershell jobs start-job

我会将foreach($computer in $computers)中的所有内容都包含在Start-Job中,以使它们同时运行。唯一的问题是,我需要等到所有工作完成才能在底部ConvertTo-Json之前完成。

$sb = "OU=some,OU=ou,DC=some,DC=domain"
$computers = Get-ADComputer -Filter {(Enabled -eq $true)} -SearchBase "$sb" -Properties *
$hasmanufacturer = New-Object System.Collections.Generic.List[System.Object]
foreach($computer in $computers)
{
    $drives = try{@(Get-WMIObject -Class Win32_CDROMDrive -Property * -ComputerName $computer.Name -ErrorAction Stop)} catch {$null}
    foreach($drive in $drives)
    {
        if($drive.Manufacturer)
        {
            $hasmanufacturer.Add($computer)
            continue
        }
    } # inner foreach
}

ConvertTo-Json $hasmanufacturer

2 个答案:

答案 0 :(得分:5)

在执行ConvertTo-Json

之前使用Get-Job | Wait-Job

答案 1 :(得分:0)

如何将计算机名称数组用作Invoke-Command的参数。默认情况下,它将运行32个并发远程会话。可以使用-Throttle参数更改号码。

$computers = Get-ADComputer -Filter {(Enabled -eq $true)} -SearchBase "OU=Servers,DC=xxx,DC=com" -Properties Name |
    Where-Object { $_.Name -match 'LAX_*' } |
    ForEach-Object { $_.Name }

$computers

$j = Invoke-Command `
    -ComputerName $computers `
    -ScriptBlock { Get-WMIObject -Class Win32_CDROMDrive -Property * -ErrorAction Stop } `
    -AsJob

while ( (Get-Job -Id $j.Id).Status -eq 'Running') {}

Get-Job -Id $j.Id | Wait-Job

$results = Receive-Job -Id $j.Id
$results