I made a reusable cmdlet from your example.
function Buffer-Pipeline {
[CmdletBinding()]
param(
$Size = 10,
[Parameter(ValueFromPipeline)]
$InputObject
)
BEGIN {
$Buffer = New-Object System.Collections.ArrayList($Size)
}
PROCESS {
[void]$Buffer.Add($_)
if ($Buffer.Count -eq $Size) {
$b = $Buffer;
$Buffer = New-Object System.Collections.ArrayList($Size)
Write-Output -NoEnumerate $b
}
}
END {
if ($Buffer.Count -ne 0) {
Write-Output -NoEnumerate $Buffer
}
}
}
Using:
@(1;2;3;4;5) | Buffer-Pipeline -Size 3 | % { "$($_.Count) items: ($($_ -join ','))" }
Output:
3 items: (1,2,3)
2 items: (4,5)
Another example:
1,2,3,4,5 | Buffer-Pipeline -Size 10 | Measure-Object
Count : 2
Processing of each batch:
1,2,3 | Buffer-Pipeline -Size 2 | % {
$_ | % { "Starting batch of $($_.Count)" } { $_ * 100 } { "Done with batch of $($_.Count)" }
}
Starting batch of 2
100
200
Done with batch of 2
Starting batch of 1
300
Done with batch of 1
source
share