Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PowerShell Job Queue

Run a job for each server in a list. I only want 5 jobs running at a time. When a job completes, it should start a new job on the next server on the list. Here's what I have so far, but I can't get it to start a new job after the first 5 jobs have ran:

   $MaxJobs = 5
   $list = Get-Content ".\list.csv"
   $Queue = New-Object System.Collections.Queue
   $CurrentJobQueue = Get-Job -State Running
   $JobQueueCount = $CurrentJobQueue.count

   ForEach($Item in $list)
  {
  Write-Host "Adding $Item to queue"
  $Queue.Enqueue($Item)
  }

 Function Global:Remote-Install
 {
 $Server = $queue.Dequeue()
 $j = Start-Job -Name $Server -ScriptBlock{

        If($JobQueueCount -gt 0)
        {
        Test-Connection $Server -Count 15
        }##EndIf
    }##EndScriptBlock

  }

For($i = 0 ;$i -lt $MaxJobs; $i++) 
{
Remote-Install
}
like image 501
Joe Brown Avatar asked Aug 12 '26 01:08

Joe Brown


1 Answers

PowerShell will do this for you if you use Invoke-Command e.g.:

Invoke-Command -ComputerName $serverArray -ScriptBlock { .. script here ..} -ThrottleLimit 5 -AsJob

BTW I don't think your use of a .NET Queue is going to work because Start-Job fires up another PowerShell process to execute the job.

like image 84
Keith Hill Avatar answered Aug 13 '26 17:08

Keith Hill



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!