Skip to content

Export-Csv/ConvertTo-Csv to better stringify complex properties #20383

@iRon7

Description

@iRon7

Summary of the new feature / enhancement

Although questionable, trying to put a structured object into a flat csv file, is a quite common question at stackoverflow (see e.g.: Getting System.Object[] issue for JSON Array data in output in PowerShell Script). This is often based on a misconception of the concerned structures, stingifying it to just the type name (as e.g. System.Object[]) is quiet pointless, instead I would expect the complex properties to have a similar value as the display format of Format-Table:

$List = [PSCustomObject]@{
  int = 1
  string = 'One'
  Array = 1, 2
  HashTable = @{ '1' = 'One'; '2' = 'Two' } # Using string keys, see: #5749
  Object = [PSCustomObject]@{ 1 = 'One'; 2 = 'Two' }
},
[PSCustomObject]@{
  int = 2
  string = 'Two'
  Array = 3, 4
  HashTable = @{ '3' = 'Three'; '4' = 'Four' }
  Object = [PSCustomObject]@{ 3 = 'Three'; 4 = 'Four' }
}

(2023-10-01: Changed hashtable to string keys for reason explained at: #5749)

Format-Table output

$List | Format-Table

int string Array  HashTable               Object
--- ------ -----  ---------               ------
  1 One    {1, 2} {[2, Two], [1, One]}    @{1=One; 2=Two}
  2 Two    {3, 4} {[4, Four], [3, Three]} @{3=Three; 4=Four}

Current ConvertTo-Csv output

$List | ConvertTo-Csv
"int","string","Array","HashTable","Object"
"1","One","System.Object[]","System.Collections.Hashtable","@{1=One; 2=Two}"
"2","Two","System.Object[]","System.Collections.Hashtable","@{3=Three; 4=Four}"

Expected ConvertTo-Csv output (wishful thinking)

$List | ConvertTo-Csv
"int","string","Array","HashTable","Object"
"1","One","{1, 2}","{[2, Two], [1, One]}","@{1=One; 2=Two}"
"2","Two","{3, 4}","{[4, Four], [3, Three]}","@{3=Three; 4=Four}"

Apart from the fact that is makes more sense, it might also help to troubleshoot and understand the situation.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Issue-Enhancementthe issue is more of a feature request than a bugNeeds-TriageThe issue is new and needs to be triaged by a work group.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions