Split up an array into chunks and start a job on each one.

Splits up a array of computer names into $n arrays, and starts a new job using each array as the argument list to the script block:


$computers = gc c:\somedir\complist.txt
$n = 6
$complists = @{}
$count = 0 
$computers |% {$complists[$count % $n] += @($_);$count++}

0..($n-1) |% {
start-job -scriptblock {gwmi win32_operatingsystem -computername $args} -argumentlist $complists[$_]
}

Advertisements

2 responses to “Split up an array into chunks and start a job on each one.

  1. Can you explain what you are doing here “$complists[$count % $n]”? I don’t understand what the % is doing to the hashtable.

  2. % is the modulus operator. It returns the remainder from the result of an integer division.

    $n = 3
    1..10 |% {$_ % $n}

    will take the numbers 1-10, divide each one by 3 and return the remainder. The result is a series that cycles through the sequence 1,2,0.
    $complists[$count % $n]
    is using those numbers as hash table keys. In effect, it’s creating one key for each number, and cycling through those 3 keys, adding computer names to the array that is the value of that key.
    The process is explained in more detail here:
    https://mjolinor.wordpress.com/2012/01/29/powershell-hash-tables-as-accumulators/

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s