Functions/Data/Split-Array.ps1
Function Split-Array { [cmdletbinding()] param ( # Array to Split [parameter(Mandatory=$true)] [object] $Array, # Count of Subarrays [parameter(Mandatory=$true,ParameterSetName="Parts")] [int] $Parts = 1, # Max Size of Subarrays [parameter(Mandatory=$true,ParameterSetName="Size")] [int] $Size = 1, # Chunking Style (Split or Queue) [Parameter(Mandatory=$false)] [ValidateSet("Split","Shuffle")] [String] $ChunkStyle = "Split" ) End { # Determine PartSize and Count based on Supplied Params switch ($PsCmdlet.ParameterSetName) { "Parts" { $PartSize_L = [Math]::Ceiling($Array.count / $parts) $PartSize_S = [Math]::Floor($Array.count / $parts) $PartCount = $Parts } "Size" { $PartSize_L = $Size $PartSize_S = $Size-1 $PartCount = [Math]::Ceiling($Array.count / $size) } } $MOD = $Array.count % $PartCount # Split Array into Parts $outArray = [System.Collections.ArrayList]::New() switch ($ChunkStyle) { "Split" { $AI = 0 $LPI = 1 for ($i=1; $i -le $PartCount; $i++) { $MyPartSize = if ($LPI -le $MOD){$PartSize_L ; $LPI++}else{$PartSize_S} $null = $outArray.add(@($Array[$AI..($AI+$MyPartSize-1)])) $AI = ($AI+$MyPartSize) } } "Shuffle" { Foreach ($Part in (0..($Parts-1))){$Null = $outArray.Add(@())} $PI=0 Foreach ($Item in $Array) { $outArray[$PI]+=$Item if($PI -eq ($Parts-1)){$PI=0}else{$PI++} } } } # Return Constructed Array of Arrays return $outArray } } |