Question:
Have done googling but have not found suitable answer
I have
1 2 3 4 5 6 7 8 9 10 11 12 13 |
$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
Answer:
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:
1 2 3 4 5 6 7 8 9 10 |
# 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 |