Code works interactively, in a PS1 file it does not. to reproduce, open powershell, paste the function and then run get-job to see the task. type get-job | remove-job when done and then put code in a PS1 file, it only runs the first two, then exits.
function RunJobFromQueue
{
if( $queue.Count -gt 0)
{
$cn = $queue.Dequeue()
$j = Start-Job -name $cn -ScriptBlock {param($x); Start-Sleep -Seconds 10;"output - " + $x} -ArgumentList $cn
Register-ObjectEvent -InputObject $j -EventName StateChanged -Action {RunJobFromQueue; Unregister-Event $eventsubscriber.SourceIdentifier; Remove-Job $eventsubscriber.SourceIdentifier } | Out-Null
}
}
$maxConcurrentJobs = 2
$jobInput = "test1", "test2", "test3", "test4", "test5", "test6"
$queue = [System.Collections.Queue]::Synchronized( (New-Object System.Collections.Queue) )
foreach($item in $jobInput) {$queue.Enqueue($item)}
for( $i = 0; $i -lt $maxConcurrentJobs; $i++){RunJobFromQueue}