PowerShell: How to Divide an Array into Smaller Chunks


You can use the following syntax in PowerShell to divide a large array into smaller chunks of equal sizes:

$my_array = 1..20
$chunk_size = 4

$counter = [pscustomobject] @{ Value = 0 }
$chunks = $my_array | Group-Object -Property { [math]::Floor($counter.Value++ / $chunk_size) }

This particular example will divide the array named $my_array (which has 20 values) into smaller arrays of size 4.

To divide an array into chunks of different sizes, simply change the value for the $chunk_size variable.

The following example shows how to use this syntax in practice.

Example: How to Divide an Array into Smaller Chunks in PowerShell

Suppose that we create an array in PowerShell named $my_array that contains the values 1 through 20.

We can use the following syntax to divide this array into chunks of size 4 each:

$my_array = 1..20
$chunk_size = 4

$counter = [pscustomobject] @{ Value = 0 }
$chunks = $my_array | Group-Object -Property { [math]::Floor($counter.Value++ / $chunk_size) }

The following screenshot shows how to use this syntax in practice:

PowerShell divide array into chunks

Notice that when we view the results of the $chunks variable we can see that the original array has been divided into five arrays that each have a size of 4.

To view the values of individual array in the output, we can use bracket notation.

For example, we can use the following syntax to view the values in the first small array in the output:

$chunks[0].Group

The following screenshot shows how to use this syntax in practice:

We can see that this array contains the values 1, 2, 3 and 4.

You can use similar syntax to retrieve the values from any of the smaller arrays produced by this code.

Related Tutorials

The following tutorials explain how to perform other common tasks in PowerShell:

PowerShell: How to Randomize Elements in an Array
PowerShell: How to Append String to Each Item in Array
PowerShell: How to Count Occurrences of Each Element in Array

Leave a Reply