如何在 PowerShell 中限制作业数 运行

How to limit the number of Jobs running in PowerShell

我的脚本在其中运行并为每个文件夹触发作业的文件夹很少。想象一下,如果我在主文件夹中有 10 个子文件夹,并且我想一次将作业数 运行 限制为 5 个。我该怎么做?我会把我的代码放在下面。

function ThrottleJob([int]$MaxJob) {
    do {
        $jobs = Get-Job -state "Running"
        Start-Sleep -Seconds 1
    } while ($jobs.Count -gt $MaxJob)
}

$folders = @()
$folders += (Get-Item $path).FullName
$folders += Get-ChildItem -Path $path -Recurse -Directory 
foreach ($folder in $folders) {
    if (Get-ChildItem -Path $folder) {
        ThrottleJob -MaxJob 5
        Start-Job -InitializationScript $allJobs -ScriptBlock { runJob -path $args[0]} -ArgumentList $folder | Out-Null
    }
} 

谁能帮帮我?

这里有一个为 Start-Job 设置阈值的示例,我相信正常的 foreach 循环会比这更快。

using namespace System.Collections.Generic
using namespace System.Management.Automation

$maxJobs = 5
$path = "$HOME\Documents"

$folders = @(
    (Get-Item $path).FullName
    (Get-ChildItem -Path $path -Recurse -Directory).FullName
)

$jobs = [List[Job]]::new()

foreach($folder in $folders)
{
    $job = Start-Job {
         Get-ChildItem $using:folder -File | Select-Object DirectoryName, Name
    }
    $jobs.Add($job)

    while(($jobs.State -eq 'Running').Count -ge $maxJobs)
    {
        Clear-Host
        Get-Job -State Running | Format-Table -AutoSize
        Start-Sleep -Seconds 1
    }
}

$result = Receive-Job $jobs -Wait -AutoRemoveJob
$result | Format-Table

如您所见,代码非常复杂。这是使用 Start-ThreadJob 的样子,它很可能比 foreach 循环更快,并且比 Start-Job.

消耗更少的内存
$maxJobs = 5
$path = "$HOME\Documents"

$folders = @(
    (Get-Item $path).FullName
    (Get-ChildItem -Path $path -Recurse -Directory).FullName
)

$jobs = foreach($folder in $folders)
{
    Start-ThreadJob {
        Get-ChildItem $using:folder -File | Select-Object DirectoryName, Name
    } -ThrottleLimit $maxJobs
}

$result = Receive-Job $jobs -Wait -AutoRemoveJob
$result | Format-Table