PowerShell: how to Split an Array into smaller Arrays (Chunks)?

Splitting an array in PowerShell into smaller arrays / chunks can come quite handy from time to time.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# Creating a new array
$inArray = @(1..20)
 
# Defining the chunk size
$chunkSize = 3
$outArray = @()
$parts = [math]::Ceiling($inArray.Length / $chunkSize)
 
# Splitting the array to chunks of the same size
for($i=0; $i -le $parts; $i++){
    $start = $i*$chunkSize
    $end = (($i+1)*$chunkSize)-1
    $outArray += ,@($inArray[$start..$end])
}
 
# Printing the output array in console
$outArray | ForEach-Object { "$_" }

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.