Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

powershell convert array of hastables into csv

Tags:

powershell

Have done googling but have not found suitable answer

I have

     $a = @(
           @{"name"="a"; "value"="1"},
           @{"name"="b"; "value"="2"}
       )

    Foreach($x in $a){
          $obj = New-object psobject
          Foreach($key in $x.keys) {
                 $obj ¦ add-member -membertype NoteProperty -name $key -value $x[$key]
           }
           $obj ¦ export-cvs test.csv
     }

I get only last line in cab. I want all the lines

like image 608
Knows Not Much Avatar asked Oct 22 '22 18:10

Knows Not Much


1 Answers

It's truth that Export-Csv won't append (< v3), but I do not think ConvertTo-Csv will solve the problem... In the end you will get file with headers repeated for every object in your array. I would suggest one of two things:

  • move Export-Csv outside foreach {} (need to put it in subexpression though, because it won't be possible to pipe it by default)
  • use Foreach-Object instead and get same results

I would also suggest to use New-Object PSObject -Property parameter instead of adding members later: because you use hashtable as a base you are half way there, see attached code samples:

# Using $( foreach ($x in $a) {} ) | Export-Csv
$(Foreach($x in $a){
    New-object psobject -Property $x
}) | Export-Csv test.csv

# Using $a | Foreach-Object {} | Export-Csv
$a | ForEach-Object { 
    New-Object PSObject -Property $_ 
} | Export-Csv test.csv
like image 165
BartekB Avatar answered Nov 03 '22 05:11

BartekB