Skip to content

Suggestion: Add a chunking (partitioning, batching) mechanism to Select-Object, analogous to Get-Content -ReadCount #8270

Closed

Description

Get-Content -ReadCount allows you to "chunk" the input lines into sub-arrays with a fixed size; e.g.:

PS> 1..5 > t.txt; Get-Content t.txt -ReadCount 2 | % { "$_" }
1 2
3 4
5

That is, the 5 lines were sent as three 2-element arrays through the pipeline (the last array has only 1 element, but is still an array).

It would be handy to have the same ability more generally in Select-Object, for chunking (partitioning) arbitrary input collections:

# Wishful thinking.
1..4 | Select-Object -ReadCount 2 | % { "$_" } # return three 2-element arrays
1 2
3 4
5

Possible combinations / mutual exclusion with existing parameters would have to be fleshed out.

Environment data

Written as of:

PowerShell Core 6.2.0-preview.1

Activity

  1. added
    Issue-Discussion
    on Nov 15, 2018
  2. BrucePay commented on Nov 26, 2018

    @BrucePay
    Collaborator

    What scenario did you have in mind for this? The one that has been discussed in the past (#7565) involved parallel computations. However, in that scenario, performance is a concern and I'm not sure a solution based on Select-Object is ideal.

  3. mklement0 commented on Nov 26, 2018

    @mklement0
    ContributorAuthor

    Partitioning for the sake of performance improvements via parallel processing of the partitions is definitely one important use of partitioning, but in this case I was thinking of partitioning for business-logic reasons, such as, say, partitioning an array of players into teams of fixed sizes.

    Here's are related (non-performance-related) SO questions:

  4. BrucePay commented on Nov 27, 2018

    @BrucePay
    Collaborator
  5. changed the title [-]Suggestion: Add a chunking (partitioning) mechanism to Select-Object, analogous to Get-Content -ReadCount[/-] [+]Suggestion: Add a chunking (partitioning, batching) mechanism to Select-Object, analogous to Get-Content -ReadCount[/+] on Apr 21, 2020
  6. iRon7 commented on Sep 12, 2022

    @iRon7

    "Burst Mode"

    As far as I can tell batching (not even implying parallel processing), by means of choking the pipeline for a while and than burst the load into batches could boost some of the succeeding cmdlets as e.g. the Set/Add-Content - and the Export-Csv cmdlet:

    Create-Batch

    see also: Slice a PowerShell array into groups of smaller arrays

    function Create-Batch {
        [CmdletBinding()]
        param (
            [ULong]$Size,
            [Parameter(Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)]$InputObject
        )
        begin {
            $Batch = [Collections.Generic.List[object]]::new()
        }
        process {
            if ($Size -and $Batch.get_Count() -ge $Size) {
                ,$Batch
                $Batch = [Collections.Generic.List[object]]::new()
            }
            $Batch.Add($_)
        }
        End {
            if ($Batch.get_Count()) { ,$Batch }
        }
    }
    # This takes about 11 seconds:
    1..1000000 |Set-Content .\test1
    # This takes about 5 seconds (even there is an addition cmdlet in the chain):
    1..1000000 |Create-Batch -Size 10000 |Set-Content .\test2
    # (All in once) takes less than 0.5 seconds:
    (,@(1..1000000)) |Set-Content .\test3
    # This takes more than 4 seconds
    1..100000 |ForEach-Object { [pscustomobject]@{ id = $_; name = "name$_" } } |Export-Csv .\test1.csv
    # This takes less than 3 secondss
    1..100000 |ForEach-Object { [pscustomobject]@{ id = $_; name = "name$_" } } |Create-Batch -Size 10000 |Export-Csv .\test2.csv
    # This takes less than 0.5 seconds:
    (,@(1..100000)) |ForEach-Object { [pscustomobject]@{ id = $_; name = "name$_"} } |Export-Csv .\test3.csv 

    (Related: #4242 Consistently document a scalar -InputObject parameter as an implementation detail or make item-by-item processing cmdlets explicitly iterate over collections)

  7. jhoneill commented on Sep 12, 2022

    @jhoneill

    iRon7 you do realise that last example creates a 1 row CSV file ?, and the the create-batch example doesn't output the right csv. ? (It's not 100000 rows of id/name, it 100000 / batch size rows with properties of the list object as columns ?

  8. iRon7 commented on Sep 12, 2022

    @iRon7

    and the the create-batch example doesn't output the right csv

    Oops, I didn't check the actual csv file as just the (display) output looks correct:

    1..5 |ForEach-Object { [pscustomobject]@{ id = $_; name = "name$_" } } |Create-Batch -Size 3
    id name
    -- ----
     1 name1
     2 name2
     3 name3
     4 name4
     5 name5
    
    (1..5 |ForEach-Object { [pscustomobject]@{ id = $_; name = "name$_" } } |Create-Batch -Size 3).Count
    2

    Which seems about right, but the Export-Csv cmdlet apparently doesn't accept "batches" (I don't see any reason why not).

    Anyways,
    I have removed the Export-Csv part from my earlier comment but that still leaves the Set/Add-Content cmdlet

  9. jhoneill commented on Sep 12, 2022

    @jhoneill

    Which seems about right, but the Export-Csv cmdlet apparently doesn't accept "batches" (I don't see any reason why not).

    Set-Content / Add-Content seem to know they should expand [Collections.Generic.List[object]] be Export-csv seems not to so exports the list's properties, not the members of the list. It might be worth opening an issue for that.

    The original point that set-content is quicker with batches, does hold.
    If Set-Content gathers content and sends it to the file at the end, adding an X-element array to the buffered items is likely to be quicker than X single adds, although when buffered data is written the file operations will be the same either way - I haven't pulled the code apart to find out if that's how it does work

    Testing these three

    1..500kb | Set-Content .\foobar.txt
    1..500kb | Create-Batch -Size 50kb | Set-Content .\foobar.txt 
    $x = 1..500KB ;  Set-Content .\foobar.txt -Value $x
    

    The first took 9.6 secs, the second 4.0 , the last 0.25. (Not using a variable shaves a few more hundredths off)

    So the best way might be to make one big batch

  10. mklement0 commented on Sep 12, 2022

    @mklement0
    ContributorAuthor

    iRon7,I think this ultimately comes down to the issue that you've already referenced in a previous comment:

    In short, the speedup comes from passing all output as a single object, and therefore calling ProcessRecord() on the downstream cmdlet only once, rather than once for each element of an enumerated collection.

    It is solely an implementation detail of Set-Content and Out-File that they perform enumeration themselves when given a collection as a whole - most cmdlets, such as Export-Csv do not do that.

    It is that implementation detail that also allows you to simply - and efficiently - pass a collection as a whole to the -InputObject parameter (-Value in the case of Set-Content) as an argument; again, this doesn't work meaningfully for most cmdlets, as discussed in the linked issue.

    Thus, the much faster alternatives to 1..1e5 | Set-Content tmp.txt and 1..1e5 | Out-Content tmp.txt are
    Set-Content tmp.txt -Value (1..1e5) and Out-File tmp.txt -InputObject (1..1e5)
    or, via the pipeline, using an aux. array to send the array as a whole:
    , (1..1e5) | Set-Content tmp.txt and , (1..1e5) | Out-File tmp.txt

    (As an aside: Out-File is much slower compared to Set-Content; while only the former uses the formatting system, which adds overhead, I'm still surprised at how large the difference is, given that integers are ultimately also just stringified by the formatting system.)

  11. iRon7 commented on Sep 12, 2022

    @iRon7

    Michael Klement (@mklement0), thanks for the comments

    It is that implementation detail that also allows you to simply - and efficiently - pass a collection as a whole to the -InputObject parameter (-Value in the case of Set-Content) as an argument; again, this doesn't work meaningfully for most cmdlets, as discussed in the linked issue.

    Agree, but the reason I started commenting in here, is that "batch processing" might give you the possibility to balance between performance and memory. Similar to the -ReadCount parameter as apposed to the -Raw parameter.

    ... most cmdlets, such as Export-Csv do not do that

    But probably the most common Write-Output cmdlet (default output) does, which actually sets the user's expectation.

  12. mklement0 commented on Sep 12, 2022

    @mklement0
    ContributorAuthor

    Understood, iRon7, but I fear that a solution is only feasible by:

    • (a) updating individual cmdlets to make them do their own enumeration of collection-as-a-whole input

    • (b) clearly documenting this support, so users become aware of it, and noting that it's up to each cmdlet whether to support it or not; this would also serve to make users aware that they need extra effort in order to implement such support in their own cmdlets.

    In

    you've suggested updating ConvertTo-Csv and Export-Csv, specifically, but it's worth compiling a comprehensive list of standard cmdlets that could benefit.

  13. mklement0 commented on Sep 12, 2022

    @mklement0
    ContributorAuthor

    To summarize:

    • The chunking mechanism suggested in this issue is motivated by business logic, not performance.

    • However, with downstream cmdlets that support performing their own enumeration of collections received as a whole, it could be used for performance optimization too (as you state).

  14. dkaszews commented on Sep 12, 2022

    @dkaszews
    Contributor

    Thinking out loud: what about allowing the chunking parameter to be a scriptblock taking context instead of a fix number? For example, it would allow something like this:

    @'
    Some command output
    That is separated 
    By empty lines
    
    After empty line
    This is a new chunk
    
    Chunks may be of different length
    '@ | Select-Object -ReadCount { $_.Length -ne 0 } | %{ $_ -join '' } 
  15. 5 remaining items

  16. dkaszews commented on Sep 13, 2022

    @dkaszews
    Contributor

    iRon7 What is the exact type returned by Get-Content $file -ReadCount 3? If it's an array, then you can't really implement what you suggest without breaking cmdlets that yield arrays, as it is not possible to distinguish them from chunks/batches. While things like arrays of arrays might be confusing to some, I think it's the only consistent way to do things without adding sharp corner cases, similar to existing cmdlets like Get-ChildItem unwrapping single results.

    I also think that "arrays of arrays" being confusing is caused by how PowerShell displays objects by default, hiding the containers, so that you can't e.g. distinguish a dict from a PSCustomObject from an array of key-value pairs. That's why we often use ConvertTo/From-Json when discussing containers, to show them exactly. I wonder if adding Format-Debug similar to Python's repr would help.

  17. iRon7 commented on Sep 13, 2022

    @iRon7

    you can't really implement what you suggest

    I can't really see why not?
    (Specifically for this feature,) you might simply flatten any array one level:

    Create-Batch (version 2)

    see also: Slice a PowerShell array into groups of smaller arrays

    function Create-Batch {
        [CmdletBinding()]
        param (
            [ULong]$Size,
            [Parameter(Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)]$InputObject
        )
        begin {
            $Batch = [Collections.Generic.List[object]]::new()
        }
        process {
            ForEach ($Item in $_) {
                if ($Size -and $Batch.get_Count() -ge $Size) {
                    ,$Batch
                    $Batch = [Collections.Generic.List[object]]::new()
                }
                $Batch.Add($Item)
            }
        }
        End {
            if ($Batch.get_Count()) { ,$Batch }
        }
    }
    0..9 |Create-Batch -Size 2 |ConvertTo-Json -Compress
    [[0,1],[2,3],[4,5],[6,7],[8,9]]
    0..9 |Create-Batch -Size 2 |Create-Batch -Size 3 |ConvertTo-Json -Compress
    [[0,1,2],[3,4,5],[6,7,8],[9]]

    (but is still something to consider)

    I wonder if adding Format-Debug similar to Python's repr would help

    I am not very known with Python, but apparently that is similar to my request: #17701 PowerShell should be better able to reveal developer information on an unknown object.

  18. jhoneill commented on Sep 13, 2022

    @jhoneill

    What I mean is:

    0..9 | Select-Object -ReadCount 2 | Select-Object -ReadCount 3 | Should -Be (ConvertFrom-Json @'
    [
      [ 0, 1, 2 ], 
      [ 3, 4, 5 ], 
      [ 6, 7, 8 ], 
      [ 9 ]
    ] 
    '@)

    This is changing the behaviour of Select object

    >   set-content 1,2,3,4,5,6,7  -Path foo.txt ;
    >  Get-Content .\foo.txt -ReadCount 2 | select -Index 2        
    5
    6
    

    If you pass array objects to Select-Object they are not unrolled and if they were, there would be no option to get the Nth array.
    Changing this is probably too big a break to be accepted.

    Although idea at the start makes sense (whatever term one uses for the arrays that result), and can help some performance issues and some business logic, I'd question whether it belongs in Select-Object .
    If someone combines -ReadCount and -Unique, do we test the array combinations for uniqueness (and does [A , B] equal [B , A]) ?
    Combined with -First / -Last and/or Skip do we group the first/last n objects, or output the first /last n arrays ?
    How often would we want to combine -ReadCount with -Property etc. (I've seen criticism of Select-Object that it does both select rows and select columns, adding "bunch objects into arrays" isn't selection)

    I also think the places where it is useful are quite limited. For Set-Content it offers a performance gain so something like
    Get-User | Select-object -Property Name -ReadCount 100 | Set-Content -File names
    Would mask a failing in Set-Content. But the real answer is to fix that (or for any logic to include batching where that makes sense.).
    TBH "Get-user" is going to take most of the time that example takes to run, so even if we reduce the Set-Content time to zero we won't see orders of magnitude improvement
    For few users (e.g. if the command is really "Get-LocalUser") it doesn't matter.
    For many users, I can see the decision going from "Can I send as one batch to help perf that I can see is/will be poor?" to a long process of what the size should be - if the command is really "Get-AdUser" and the directory is 128K users, do I divide into 2 64K chunks? or 64 2K chunks? Or 2K chunks of 64 each ? And when the next person looks at the code they need to find out why chunks of 512 were chosen. Extra time writing and maintaining the code cancels out the saved run time :-(
    (see https://jhoneill.github.io/powershell/2019/11/10/Arrays-DontSweatSmallStuff.html)

    iRon7 it may be best to make this available as a community command. (I'm on the cmdlet working group, and I can't speak for everyone else, but I'd predict this would get a response of "Good idea, better done by the community"). Despite the limits of where it is useful, where it does have value it probably has a lot of value.
    Note that in V2 you've broken this form Create-Batch -Size 10 (1..60) - you can also have "a -NoUnroll" option to batch to arrays of arrays.

    PowerShell (or PWSH if you prefer). Devops (especially Azure Devops), Photography, and general thoughts
  19. dkaszews commented on Sep 13, 2022

    @dkaszews
    Contributor

    James O'Neill (@jhoneill) Putting it into a separate command makes sense, otherwise we're running risk of some unintuitive behavior when what we are selecting is also a collection. Letting community develop it as a separate module, maybe to pull it later in the future does make sense, as making it a new cmdlet negates any need to put it into the core repo, maybe save for some code reuse.

    iRon7 Is the code you pasted above written for sake of the example, or do you have a public repo we could use for developing such a module?

  20. iRon7 commented on Sep 13, 2022

    @iRon7

    I also agree that putting it in separate command makes sense.

    Is the code you pasted above written for sake of the example, or do you have a public repo

    Yes and yes, I have quickly setup a new repo: https://github.com/iRon7/Create-Batch/
    At the moment I am too busy to add more to it but plan to do it later.
    The contribution from my side can only be PowerShell based script or module (as I lack the C# knowledge), the initial idea, testing and some basic descriptions (as I am not native English).

  21. mklement0 commented on Sep 14, 2022

    @mklement0
    ContributorAuthor
    • Dominik Kowalski (@dkaszews), I like your suggestion: it amounts to a very flexible batching mechanism.

    • iRon7, I also don't think that a batching command should re-batch: it should be up to any upstream cmdlet to stream the objects to be batched as-is.

    • As for where the functionality belongs / naming:

      • Conceptually, I think it makes sense to extend Select-Object, as "select every N objects" seems like a similar operation to "select the first / last N" objects.
      • However, from an implementation perspective I can see why packing more into Select-Object may be problematic.
      • If a new cmdlet is implemented, I suggest sticking with the Select verb, such as Select-Batch
  22. dkaszews commented on Sep 14, 2022

    @dkaszews
    Contributor

    I'll try to cook something up in iRon7 's repo, I was thinking of naming it Select-Many like in C# LINQ, but Michael Klement (@mklement0) 's Select-Batch also makes sense if it allows both flattening and chunking. Or we could just throw a bunch of stuff together and think about cleaning it up once it takes shape.

  23. added
    Resolution-No Activity
    on Nov 16, 2023
  24. iRon7 commented on Nov 16, 2023

    @iRon7

    Please either mark this issue with something like Resolution-Declined or put it on a kind of wishlist "Issue we would like to prioritize, but we can't commit we will get to it yet

  25. iRon7 commented on Feb 4, 2025

    @iRon7

    Android-listview-deathly, I suspect you accidentally put your comment/link in here (using unfurl-links?). If that is the case, can you remove it or otherwise add some context to the comment about the relation with the initial propose.

  26. groutoutlook commented on Oct 5, 2025

    @groutoutlook

    holy, the inactivity bot, go away please.

    EDIT: btw thanks iRon7 for your solutions in Slice a PowerShell array into groups of smaller arrays.😉

    As now I have to rename it to either Select-Batch or Split-Batch so verb-noun police wont arrest me.
    See my copied code.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Issue-DiscussionResolution-No ActivityWG-Cmdlets

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions