You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Suggestion: Add a chunking (partitioning, batching) mechanism to Select-Object, analogous to Get-Content -ReadCount #8270
Issue-Discussionthe issue may not have a clear classification yet. The issue may generate an RFC or may be reclassifResolution-No ActivityIssue has had no activity for 6 months or moreWG-Cmdletsgeneral cmdlet issues
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.
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:
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
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:
functionCreate-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 seconds1..100000|ForEach-Object { [pscustomobject]@{ id=$_; name="name$_" } } |Export-Csv .\test1.csv
# This takes less than 3 secondss1..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
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 ?
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
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.)
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 commonWrite-Output cmdlet (default output) does, which actually sets the user's expectation.
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.
you've suggested updating ConvertTo-Csv and Export-Csv, specifically, but it's worth compiling a comprehensive list of standard cmdlets that could benefit.
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).
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 outputThat is separated By empty linesAfter empty lineThis is a new chunkChunks may be of different length'@|Select-Object-ReadCount { $_.Length-ne0 } |%{ $_-join'' }
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.
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.
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?
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).
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
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.
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.
Issue-Discussionthe issue may not have a clear classification yet. The issue may generate an RFC or may be reclassifResolution-No ActivityIssue has had no activity for 6 months or moreWG-Cmdletsgeneral cmdlet issues
Activity
BrucePay commentedon Nov 26, 2018
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-Objectis ideal.mklement0 commentedon Nov 26, 2018
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:
BrucePay commentedon Nov 27, 2018
Michael Klement (@mklement0) Thanks!
[-]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[/+]iRon7 commentedon Sep 12, 2022
"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 theExport-Csvcmdlet:Create-Batch
see also: Slice a PowerShell array into groups of smaller arrays
(Related: #4242 Consistently document a scalar
-InputObjectparameter as an implementation detail or make item-by-item processing cmdlets explicitly iterate over collections)jhoneill commentedon Sep 12, 2022
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 ?
iRon7 commentedon Sep 12, 2022
Oops, I didn't check the actual
csvfile as just the (display) output looks correct:Which seems about right, but the
Export-Csvcmdlet apparently doesn't accept "batches" (I don't see any reason why not).Anyways,
I have removed the
Export-Csvpart from my earlier comment but that still leaves theSet/Add-Contentcmdletjhoneill commentedon Sep 12, 2022
Set-Content/Add-Contentseem to know they should expand[Collections.Generic.List[object]]beExport-csvseems 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-contentis quicker with batches, does hold.If
Set-Contentgathers 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 workTesting these three
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
mklement0 commentedon Sep 12, 2022
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-ContentandOut-Filethat they perform enumeration themselves when given a collection as a whole - most cmdlets, such asExport-Csvdo not do that.It is that implementation detail that also allows you to simply - and efficiently - pass a collection as a whole to the
-InputObjectparameter (-Valuein the case ofSet-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.txtand1..1e5 | Out-Content tmp.txtareSet-Content tmp.txt -Value (1..1e5)andOut-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.txtand, (1..1e5) | Out-File tmp.txt(As an aside:
Out-Fileis much slower compared toSet-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.)iRon7 commentedon Sep 12, 2022
Michael Klement (@mklement0), thanks for the comments
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
-ReadCountparameter as apposed to the-Rawparameter.But probably the most common
Write-Outputcmdlet (default output) does, which actually sets the user's expectation.mklement0 commentedon Sep 12, 2022
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
ConvertTo-CsvandExport-Csvshould unroll (embedded) arrays and lists #18071you've suggested updating
ConvertTo-CsvandExport-Csv, specifically, but it's worth compiling a comprehensive list of standard cmdlets that could benefit.mklement0 commentedon Sep 12, 2022
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).
dkaszews commentedon Sep 12, 2022
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:
5 remaining items
dkaszews commentedon Sep 13, 2022
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 likeGet-ChildItemunwrapping 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
PSCustomObjectfrom an array of key-value pairs. That's why we often useConvertTo/From-Jsonwhen discussing containers, to show them exactly. I wonder if addingFormat-Debugsimilar to Python'sreprwould help.iRon7 commentedon Sep 13, 2022
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
(but is still something to consider)
I am not very known with Python, but apparently that is similar to my request:
#17701PowerShell should be better able to reveal developer information on an unknown object.jhoneill commentedon Sep 13, 2022
This is changing the behaviour of Select object
If you pass array objects to
Select-Objectthey 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
-ReadCountand-Unique, do we test the array combinations for uniqueness (and does [A , B] equal [B , A]) ?Combined with
-First/-Lastand/orSkipdo we group the first/last n objects, or output the first /last n arrays ?How often would we want to combine
-ReadCountwith-Propertyetc. (I've seen criticism ofSelect-Objectthat 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-Contentit offers a performance gain so something likeGet-User | Select-object -Property Name -ReadCount 100 | Set-Content -File namesWould 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-Contenttime to zero we won't see orders of magnitude improvementFor 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.dkaszews commentedon Sep 13, 2022
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?
iRon7 commentedon Sep 13, 2022
I also agree that putting it in separate command makes sense.
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).
mklement0 commentedon Sep 14, 2022
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:
Select-Object, as "select every N objects" seems like a similar operation to "select the first / last N" objects.Select-Objectmay be problematic.Selectverb, such asSelect-Batchdkaszews commentedon Sep 14, 2022
I'll try to cook something up in iRon7 's repo, I was thinking of naming it
Select-Manylike in C# LINQ, but Michael Klement (@mklement0) 'sSelect-Batchalso 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.iRon7 commentedon Nov 16, 2023
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
iRon7 commentedon Feb 4, 2025
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.
groutoutlook commentedon Oct 5, 2025
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-BatchorSplit-Batchso verb-noun police wont arrest me.See my copied code.