Use PowerShell to run virus scan on multiple servers

Solution 1:

I'm using something like this for running tasks in parallel on remote hosts:

$maxSlots = 10
$hosts = "foo", "bar", "baz", ...

$job = {
  Invoke-Command -ScriptBlock { Scan32.exe } -Computer $ARGV[0] -ThrottleLimit 10 -Authentication domain/admin
}

$queue = [System.Collections.Queue]::Synchronized((New-Object System.Collections.Queue))
$hosts | ForEach-Object { $queue.Enqueue($_) }

while ( $queue.Count -gt 0 -or @(Get-Job -State Running).Count -gt 0 ) {
  $freeSlots = $maxSlots - @(Get-Job -State Running).Count
  for ( $i = $freeSlots; $i -gt 0 -and $queue.Count -gt 0; $i-- ) {
    Start-Job -ScriptBlock $job -ArgumentList $queue.Dequeue() | Out-Null
  }
  Get-Job -State Completed | ForEach-Object {
    Receive-Job -Id $_.Id
    Remove-Job -Id $_.Id
  }
  Sleep -Milliseconds 100
}

# Remove all remaining jobs.
Get-Job | ForEach-Object {
  Receive-Job -Id $_.Id
  Remove-Job -Id $_.Id
}