Lazy Diary @ Hatena Blog

PowerShell / Java / miscellaneous things about software development, Tips & Gochas. CC BY-SA 4.0/Apache License 2.0

Convert an array to CSV with PowerShell

Problem

You cannot convert an array with just pipeline the array to ConvertTo-Csv.

PS > $array = ("a", "b", "c", "a", "d")
PS > $array | ConvertTo-Csv
"Length"
"1"
"1"
"1"
"1"
"1"

... or just passing the array to ConvertTo-Csv.

PS > ConvertTo-Csv $array
"Length","LongLength","Rank","SyncRoot","IsReadOnly","IsFixedSize","IsSynchronized","Count"
"5","5","1","System.Object[]","False","True","False","5"

An array in object also will produce undesired result.

PS > $obj = New-Object PSObject
PS > $obj | Add-Member -MemberType NoteProperty -Name "CSV" -Value $array
PS > $obj | ConvertTo-Csv
"CSV"
"System.Object[]"
PS > ConvertTo-Csv $obj
"CSV"
"System.Object[]"

Reason

It seems by design.

Solution

You should use Add-Member with an loop and dummy property names.

PS > $obj = New-Object PSObject
PS > for ($i=0; $i -lt $array.Length; $i++) { $obj | Add-Member -MemberType NoteProperty -Name $i -Value $array[$i] }
PS > $obj | ConvertTo-Csv -NoTypeInformation | Select-Object -Skip 1
"a","b","c","a","d"