Jump to page sections
I wrote a couple of advanced functions (it's just a few lines of code) for splitting an array/collection into chunks/parts for later processing in the pipeline (or otherwise) as smaller arrays. It's pretty simple, but quite useful for a number of scenarios. I've found myself needing this from time to time, so I finally decided to write a generic version of it.Its performance on very large collections won't be too good, but I haven't actually benchmarked it or tested it extensively (yet). Array concatenation is something PowerShell does not do efficiently (I seem to remember the reasons for this being good though (creating a copy of the array)), and array concatenation seems difficult to avoid, and is used in this cmdlet, so there will be a performance penalty due to that.
I'm putting up two versions. The version called Split-Collection.ps1.txt works only with pipeline input The other one, called Split-CollectionParam.ps1.txt, also works correctly on a collection passed in as the parameter -Collection. In the latter version I use foreach () on the collection, which enumerates the entire collection and thus potentially could be more memory-intensive than the version working strictly with pipeline input, one element at the time, but you might see a performance gain as foreach loops are generally a lot faster than ForEach-Object. The latter one (with param) is more versatile as it works with both pipeline input and input passed as a parameter and would generally be recommended unless you know you need the other one.Examples
PS C:\> 1..10 | Split-Collection -Count 2 | %{ $_ -join ', ' }
1, 2
3, 4
5, 6
7, 8
9, 10
PS C:\> (1..10 | Split-Collection -Count 2 | %{ $_ -join ', ' }).Count
5
PS C:\> 1..10 | Split-Collection -Count 5 | %{ $_ -join ', ' }
1, 2, 3, 4, 5
6, 7, 8, 9, 10
PS C:\> (1..10 | Split-Collection -Count 5 | %{ $_ -join ', ' }).Count
2
And you also get the remainder (requires its own logic...) if it doesn't divide evenly:
PS C:\> 1..10 | Split-Collection -Count 3 | %{ $_ -join ', ' }
1, 2, 3
4, 5, 6
7, 8, 9
10
PS C:\> (1..10 | Split-Collection -Count 3 | %{ $_ -join ', ' }).Count
4
Here's an example where I dot-source Split-CollectionParam.ps1 ("the second version") and pass in a collection as a parameter.
PS D:\> . D:\Dropbox\PowerShell\Split-CollectionParam.ps1
PS D:\> Split-Collection -Collection (1..10) -Count 5 | %{ $_ -join ', ' }
1, 2, 3, 4, 5
6, 7, 8, 9, 10
PS D:\> (Split-Collection -Collection (1..10) -Count 5 | %{ $_ -join ', ' }).Count
2
Code
Split-CollectionParam.ps1.txt
function Split-Collection {
[CmdletBinding()]
param(
[Parameter(ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)] $Collection,
[Parameter(Mandatory=$true)][ValidateRange(1, 247483647)][int] $Count)
begin {
$Ctr = 0
$Array = @()
$TempArray = @()
}
process {
foreach ($e in $Collection) {
if (++$Ctr -eq $Count) {
$Ctr = 0
$Array += , @($TempArray + $e)
$TempArray = @()
continue
}
$TempArray += $e
}
}
end {
if ($TempArray) { $Array += , $TempArray }
$Array
}
}
Split-Collection.ps1.txt
function Split-Collection {
[CmdletBinding()]
param(
[Parameter(ValueFromPipeline=$true)] $Collection,
[Parameter(Mandatory=$true)][ValidateRange(1, 247483647)][int] $Count)
begin {
$Ctr = 0
$Arrays = @()
$TempArray = @()
}
process {
if (++$Ctr -eq $Count) {
$Ctr = 0
$Arrays += , @($TempArray + $_)
$TempArray = @()
return
}
$TempArray += $_
}
end {
if ($TempArray) { $Arrays += , $TempArray }
$Arrays
}
}
Download
''2014-01-11: Put up two versions and documented briefly.
''2014-01-11: Renamed the parameter -ChunkSize to -Count.'' Powershell WindowsBlog articles in alphabetical order
A
- A Look at the KLP AksjeNorden Index Mutual Fund
- A primitive hex version of the seq gnu utility, written in perl
- Accessing the Bing Search API v5 using PowerShell
- Accessing the Google Custom Search API using PowerShell
- Active directory password expiration notification
- Aksje-, fonds- og ETF-utbytterapportgenerator for Nordnet-transaksjonslogg
- Ascii art characters powershell script
- Automatically delete old IIS logs with PowerShell
C
- Calculate and enumerate subnets with PSipcalc
- Calculate the trend for financial products based on close rates
- Check for open TCP ports using PowerShell
- Check if an AD user exists with Get-ADUser
- Check when servers were last patched with Windows Update via COM or WSUS
- Compiling or packaging an executable from perl code on windows
- Convert between Windows and Unix epoch with Python and Perl
- Convert file encoding using linux and iconv
- Convert from most encodings to utf8 with powershell
- ConvertTo-Json for PowerShell version 2
- Create cryptographically secure and pseudorandom data with PowerShell
- Crypto is here - and it is not going away
- Crypto logo analysis ftw
D
G
- Get rid of Psychology in the Stock Markets
- Get Folder Size with PowerShell, Blazingly Fast
- Get Linux disk space report in PowerShell
- Get-Weather cmdlet for PowerShell, using the OpenWeatherMap API
- Get-wmiobject wrapper
- Getting computer information using powershell
- Getting computer models in a domain using Powershell
- Getting computer names from AD using Powershell
- Getting usernames from active directory with powershell
- Gnu seq on steroids with hex support and descending ranges
- Gullpriser hos Gullbanken mot spotprisen til gull
H
- Have PowerShell trigger an action when CPU or memory usage reaches certain values
- Historical view of the SnP 500 Index since 1927, when corona is rampant in mid-March 2020
- How Many Bitcoins (BTC) Are Lost
- How many people own 1 full BTC
- How to check perl module version
- How to list all AD computer object properties
- Hva det innebærer at særkravet for lån til sekundærbolig bortfaller
I
L
M
P
- Parse openssl certificate date output into .NET DateTime objects
- Parse PsLoggedOn.exe Output with PowerShell
- Parse schtasks.exe Output with PowerShell
- Perl on windows
- Port scan subnets with PSnmap for PowerShell
- PowerShell Relative Strength Index (RSI) Calculator
- PowerShell .NET regex to validate IPv6 address (RFC-compliant)
- PowerShell benchmarking module built around Measure-Command
- Powershell change the wmi timeout value
- PowerShell check if file exists
- Powershell check if folder exists
- PowerShell Cmdlet for Splitting an Array
- PowerShell Executables File System Locations
- PowerShell foreach loops and ForEach-Object
- PowerShell Get-MountPointData Cmdlet
- PowerShell Java Auto-Update Script
- Powershell multi-line comments
- Powershell prompt for password convert securestring to plain text
- Powershell psexec wrapper
- PowerShell regex to accurately match IPv4 address (0-255 only)
- Powershell regular expressions
- Powershell split operator
- Powershell vs perl at text processing
- PS2CMD - embed PowerShell code in a batch file
R
- Recursively Remove Empty Folders, using PowerShell
- Remote control mom via PowerShell and TeamViewer
- Remove empty elements from an array in PowerShell
- Remove first or last n characters from a string in PowerShell
- Rename unix utility - windows port
- Renaming files using PowerShell
- Running perl one-liners and scripts from powershell
S
- Sammenlign gullpriser og sølvpriser hos norske forhandlere av edelmetall
- Self-contained batch file with perl code
- Silver - The Underrated Investment
- Simple Morningstar Fund Report Script
- Sølv - den undervurderte investeringen
- Sort a list of computers by domain first and then name, using PowerShell
- Sort strings with numbers more humanely in PowerShell
- Sorting in ascending and descending order simultaneously in PowerShell
- Spar en slant med en optimalisert kredittkortportefølje
- Spre finansiell risiko på en skattesmart måte med flere Aksjesparekontoer
- SSH from PowerShell using the SSH.NET library
- SSH-Sessions Add-on with SCP SFTP Support
- Static Mutual Fund Portfolio the Last 2 Years Up 43 Percent
- STOXR - Currency Conversion Software - Open Exchange Rates API