How to split an array in windows powershell

When running multiple jobs we can split an array to work with each separately.
Below I have wrote this Powershell function which we can utilize to split array.

Usage Examples:

Lets say you have 20K Mailboxes in your organization, you have to run some script against each one, running script for entire 20K Mailboxes will take a lot of time, so you decided to run multiple jobs, which would require you to split the work, using this function give you ability to split an array into multiple arrays.

So next we will see how we can split the array.
To Split the Array into 10 import the function and run the CMD like below.

$allMailboxes=Get-Mailbox -ResultSize Unlimited
Split-Array -arraytoSplit $allMailboxes -NoofarraytoSplit 10

Now you can run script again each array in $10Arrays, below the function which you can add into your script or your module.
function split-Array {        

param ([object[]]$arraytoSplit, [int]$NoofarraytoSplit)

$SplitSize=[math]::Round($arraytoSplit.count/$NoofarraytoSplit)
            $TotalSize = $arraytoSplit.Count
for ($Index = 0; $Index -lt $TotalSize; $Index += $SplitSize)
{
, ($arraytoSplit[$index .. ($index + $splitSize - 1)])
}
}

Comments