by denBen at 2013-04-23 04:48:29

I’m trying to create a small function to split a big array into smaller arrays.by denBen at 2013-04-23 04:54:04

(I wanted to archive a large number of files into multiple zip files)

I wanted to provide two ways of determening the size of the partial arrays:

either a fixed number of items per subarray.

Either a division of the total number of items.

The first one is easy and fast, as I could keep the pipeline working.

For the second I need to complete input collection and therefor can’t ouput each subarray as the pipiline resolves itself.

I have created a little function that works great for the first case, where I just output a partial array every so many items.

The second case, based on the total number of items, doesn’t work. My $NumberOfItemsPerPart equals 0

But I really want it to work. (please… please?)

I have found a way to make both cases work, see the second code block, but that solution isn’t as elegant as I would like it to be.

I also use the same algoritm twice, which is… bad.

I’m hoping that you might know how to alter the first code block in order to make it work in both scenarios.`function Split-Array{`

param(

[Parameter(Mandatory=$true, Position=0, ValueFromPipeline=$True)]

[Array]$InputObject,

[Parameter(ParameterSetName="BasedOnTotalSize")]

[int]$NumberOfParts,

[Parameter(ParameterSetName="BasedOnItems")]

[int]$ItemsPerPart,

[Parameter(Mandatory=$false)]

$LogFile

)

begin{

$ItemCounter = 0

$ItemContainer = @()

if($ItemsPerPart) { $NumberOfItemsPerPart = $ItemsPerPart }

if($NumberOfParts) { $NumberOfItemsPerPart = [Math]::Ceiling(@($input).count / $NumberOfParts) }

}

process {

$ItemContainer += $

$ItemCounter++

if($ItemCounter -eq $NumberOfItemsPerPart){

, $ItemContainer

$ItemContainer = @()

$ItemCounter = 0

}

}

end {

}

}`function Split-Array{`

param(

[Parameter(Mandatory=$true, Position=0, ValueFromPipeline=$True)]

[Array]$InputObject,

[Parameter(ParameterSetName="BasedOnTotalSize")]

[int]$NumberOfParts,

[Parameter(ParameterSetName="BasedOnItems")]

[int]$ItemsPerPart,

[Parameter(Mandatory=$false)]

$LogFile

)

begin{

$ItemCounter = 0

$ItemContainer = @()

$TotalInput = @()

if($ItemsPerPart){ $NumberOfItemsPerPart = $ItemsPerPart }

}

process {

if ($ItemsPerPart){

$ItemContainer += $

$ItemCounter++

if($ItemCounter -eq $NumberOfItemsPerPart){

, $ItemContainer

$ItemContainer = @()

$ItemCounter = 0

}

}

if($NumberOfParts){

$TotalInput += $

}

}

end {

if($NumberOfParts){

$NumberOfItemsPerPart = [Math]::Ceiling($TotalInput.count / $NumberOfParts)

$TotalInput | foreach {

$ItemContainer += $

$ItemCounter++

if($ItemCounter -eq $NumberOfItemsPerPart){

, $ItemContainer

$ItemContainer = @()

$ItemCounter = 0

}

}

}

}

}

Oh, in case anyone knows:

I don’t like the syntax`, $ItemContainer`

It’s not very reader friendly.

Is there an alternative?