Skip to content

ConvertTo-Csv and Export-Csv should unroll (embedded) arrays and lists #18071

Closed

Description

@iRon7

Prerequisites

Steps to reproduce

Knowing that the -InputObject "Specifies the objects that are converted to CSV strings", I would expect that any embedded array or list to unroll into objects (see also: Suggestion: Add a chunking (partitioning, batching) mechanism to Select-Object, analogous to Get-Content -ReadCount)

$List = 1..5 |ForEach-Object {
    [pscustomobject]@{ id = $_; name = "name$_" }
}

,$List |ConvertTo-Csv

Expected behavior

"id","name"
"1","name1"
"2","name2"
"3","name3"
"4","name4"
"5","name5"

Similar to:

$List |Convert-Csv # Without an unary comma

and to what Add-Content and Set-Content does for:

,(1..5) |Set-Content .\MyFile.txt

Or simply as it is being output:

,$List

id name
-- ----
 1 name1
 2 name2
 3 name3
 4 name4
 5 name5

Actual behavior

"Length","LongLength","Rank","SyncRoot","IsReadOnly","IsFixedSize","IsSynchronized","Count"
"5","5","1","System.Object[]","False","True","False","5"

Error details

No Error

Environment data

Name                           Value
----                           -----
PSVersion                      7.2.6
PSEdition                      Core
GitCommitId                    7.2.6
OS                             Microsoft Windows 10.0.22000
Platform                       Win32NT
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0…}
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1
WSManStackVersion              3.0

Visuals

No response

Activity

  1. added
    Needs-Triage
    on Sep 12, 2022
  2. changed the title [-]`ConvertTo-Csv` and `Export-Csv` should unroll collections[/-] [+]`ConvertTo-Csv` and `Export-Csv` should unroll arrays and lists[/+] on Sep 12, 2022
  3. changed the title [-]`ConvertTo-Csv` and `Export-Csv` should unroll arrays and lists[/-] [+]`ConvertTo-Csv` and `Export-Csv` should unroll (embedded) arrays and lists[/+] on Sep 12, 2022
  4. jhoneill commented on Sep 12, 2022

    @jhoneill

    As a side effect
    ConvertTo-Csv $list
    would also work. Generally there needs to be a very good reason why $x | cmdlet does something different from cmdlet $x, and I've never seen why this is an exception (ConvertTo-Json enumerates items, but convertTo-Csv outputs properties of the list object).

  5. SteveL-MSFT commented on Sep 12, 2022

    @SteveL-MSFT
    Member

    The comma that precedes the array in the examples above explicitly makes the array a single object that passes through the pipeline vs each element of the array/collection being passed to the cmdlet. So in this case, the cmdlet sees it as a single object (keep in mind it could have also been an array of arrays) and serializes it as such vs unrolling the collection. So this is working by-design so that the user can differentiate treating an array as a collection or a single object through the pipeline.

  6. added
    Resolution-Answered
    and removed
    Needs-Triage
    on Sep 12, 2022
  7. mklement0 commented on Sep 12, 2022

    @mklement0
    Contributor

    iRon7, based on the conversation in #8270, I encourage you to open a new issue that explains the rationale for your suggestion in more detail.

    Steve Lee (@SteveL-MSFT), the underlying idea is to intentionally allow ConvertTo-Csv and Export-Csv to accept collections as a whole for the sake of improved processing speed (at the expense of memory consumption).

    Set-Content and Out-File (and Write-Output) already do that, but it's especially compelling with ConvertTo-Csv and Export-Csv (and possibly others), where doing anything other than enumerating a collection passed as a single object serves no useful purpose (in other words: the current behavior in that case is useless).

    James O'Neill (@jhoneill):

    Generally there needs to be a very good reason why $x | cmdlet does something different from cmdlet $x

    The reason for the fundamental difference is that $x is implicitly enumerated in the pipeline, which doesn't happen if $x is passed as an argument. That is, cmdlet sees the elements of $x as input, one by one, in the pipeline scenario, whereas it sees $x as a whole in the argument scenario.

    provides the backstory.

  8. SteveL-MSFT commented on Sep 12, 2022

    @SteveL-MSFT
    Member

    Michael Klement (@mklement0) if the request is an optimization to unroll a collection in the cmdlet vs via the pipeline, then would a -InputCollection parameter make sense?

  9. jhoneill commented on Sep 12, 2022

    @jhoneill

    James O'Neill (@jhoneill):

    Generally there needs to be a very good reason why $x | cmdlet does something different from cmdlet $x

    The reason for the fundamental difference is that $x is implicitly enumerated in the pipeline, which doesn't happen if $x is passed as an argument.

    Michael Klement (@mklement0)

    Yes, I'm well aware of that.
    There's an expectation that commands do the work need so that
    cmdlet $x, $y , $z or $x, $y, $z | cmdlet or $a = @($x, $y, $z) ; cmdlet $a
    give the same result. There are a few cases where that wouldn't make sense, but where it would...

  10. mklement0 commented on Sep 12, 2022

    @mklement0
    Contributor

    James O'Neill (@jhoneill), my point was that given how pipeline-binding parameters currently work, you shouldn't have this expectation - as desirable as this symmetry may be - and if you do, you'll be disappointed, with only a few, not documented-as-such exceptions.

    As noted before, the only solution that would provide performance benefits is to make all cmdlets where this symmetry makes sense explicitly do their own enumeration.

    A general solution, as part of the plumbing - which would not be (meaningfully) performance-enhancing, unfortunately - is suggested here.

  11. mklement0 commented on Sep 12, 2022

    @mklement0
    Contributor

    Given the above, Steve Lee (@SteveL-MSFT), I don't think a separate parameter is called for.

    What would make sense is to do a systematic review of all standard cmdlets and decide which ones should perform their own enumeration without ambiguity (i.e. those cmdlets for which not enumerating results in useless behavior), and update those (I haven't done this review, and it's possible that ConvertTo-Csv and Export-Csv are the only candidates).

    Separately, implementing the (opt-in) plumbing solution mentioned above makes sense to me, even if it doesn't result in performance gains.

  12. iRon7 commented on Sep 13, 2022

    @iRon7
    Author

    The reason that I actually opened a bug report for this and not a feature request is because aside for the possible performance improvement, this statement

    this is working by-design so that the user can differentiate treating an array as a collection or a single object through the pipeline.

    might be generally correct but is pointless for the ConvertTo-Csv - and Export-Csv which are only able to generate flat csv lists by their design (in my opinion, the particular cmdlet design goals should take president over the general design goal).
    Also note that this general statement doesn't apply to the Set-Content/ Add-Content cmdlets and for the default display output (Write-Output cmdlet) where the user (script author) isn't actually able to differentiate between an array or a single object (see also: #17701).

    There are a few cases in stackoverflow questions that relate to this expectation where regardless of whether I supply the groups via the pipeline or via a parameter argument, one might (could) only expect a flat csv list as an output (see also: #3865 Export-Csv -InputObject and ConvertTo-Csv -InputObject export/convert the collection object itself rather than its elements):

    $Process = Get-Process | Group-Object -Property PriorityClass
    ConvertTo-Csv $Process.Group
    
    "Length","LongLength","Rank","SyncRoot","IsReadOnly","IsFixedSize","IsSynchronized","Count" # is bogus
    "258","258","1","System.Object[]","False","True","False","258"
  13. jhoneill commented on Sep 13, 2022

    @jhoneill

    James O'Neill (@jhoneill), my point was that given how pipeline-binding parameters currently work, you shouldn't have this expectation - as desirable as this symmetry may be - and if you do, you'll be disappointed, with only a few, not documented-as-such exceptions.

    Michael Klement (@mklement0) yes I think we understand each other. That expectation grows up because that's how well written commands work. PowerShell classes teach people that foreach ($f in $files) {Invoke-Something $f} is rarely necessary and $files | inovke-Something or invoke-Something $files is "normal", and that they should write new commands to work that way.

    Your later description that in some cases " not enumerating results in useless behavior " sums it up neatly :-) Useless, and (I think) often unexpected

    Some things like Get-Member, do the right thing by not enumerating, (how else do we learn about the enumerable object ? ) For export-CSV it's the wrong thing - and finding and fixing similar cases would be a benefit.

  14. ghost closed this as completedon Sep 14, 2022
  15. iRon7 commented on Sep 14, 2022

    @iRon7
    Author

    As explained, I would like the general closure statement in this issue to be reconsidered and more specific towards the concerned ConvertTo-Csv and Export-Csv cmdlets.
    In other words, can this issue been reopened and the Resolution-Answered label removed to prevent it from automatically being closed again.

  16. mklement0 commented on Sep 14, 2022

    @mklement0
    Contributor

    iRon7, I agree that this is worth tackling, but in a generalized manner - which amounts to a nontrivial amount of work:

    I forgot that I did try to compile a list of all cmdlets where passing arrays as a whole results in unless behavior, namely those in Category C from #4242 (additions / corrections welcome).

    Thus, as that issue's title states, one possible resolution - and to me the preferred one - is to make all cmdlets in that category do their own enumeration of collections received as single objects.

    #4242 has languished for 5 years now, and it is focused on the -InputObject-vs.-pipeline asymmetry.
    But as this discussion here shows, it also prevents chunked input from the pipeline.

    So the question is whether there's a willingness to tackle this, bot for the sake of invocation symmetry and, perhaps more importantly, for the performance benefits it offers.

  17. jhoneill commented on Sep 14, 2022

    @jhoneill

    Michael Klement (@mklement0) I'm looking at your category C items with a view to taking them to the cmdlet working group

    There might be some quibbles about what is truly in category C. With Where-object, someone somewhere is bound to want to use the count of members or even -is [Array] in a where condition. But the list is a helpful place to start from.

  18. mklement0 commented on Sep 14, 2022

    @mklement0
    Contributor

    Thanks, James O'Neill (@jhoneill) - cmdlet-specific evaluation is definitely called for.

    In that context, revisiting how the pipeline-binding parameters are typed is also worthwhile (object[] vs. object), as discussed in #4242, and with respect to performance, particularly, in #18070 (comment)

    Worth noting: #4242, which was focused on just by-argument parameter binding without batching via the pipeline being in the picture, discusses assuming that pipeline input is already enumerated and performing the cmdlet-internal enumeration only for argument-bound values.

    In order to support batching, however, this distinction mustn't be made.

  19. jhoneill commented on Sep 14, 2022

    @jhoneill

    Michael Klement (@mklement0) Yes, I was just reading the comment the 18070, and if for anything which looks at the InputObject parameter generally, the object vs Object[] question should be on the radar.
    I wonder, without having checked, if the commands which unroll arrays tend towards having Object[] and the ones which don't towards Object

    When I'm coding in PowerShell I leave InputObject as object (which is implied so I don't need to have it in the param block), and where a process block would be

    Process { 
      Do_stuff_with $InputObject
    }
    

    I typically have

    Process {
        foreach ($i in  $InputObject ) {
          Do_stuff_with $i
        }
    }
    

    I don't spend enough time in c# to know if that is equally easy to do there - PowerShell is very tolerant of
    foreach ($i in $ScalarVariable) but this simple change means if the object is an array it unrolls (one level, not nested arrays) and if its scalar it processes as normal.

  20. mklement0 commented on Sep 14, 2022

    @mklement0
    Contributor

    A quick look suggests that only Set-Content / Add-Content and Join-String have psobject[] parameters, not the other ones in Category B - as discussed, psobject[] / object[] parameters best avoided so as not to create array-allocation overhead with scalar input objects from the pipeline.

    In C# you cannot directly enumerate scalars with foreach, so reflection is needed to check if a given object is an enumerable.

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

    Resolution-Answered

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions