Export-CSV exports length but not name

这一生的挚爱 提交于 2019-11-26 22:50:57
mjolinor

Export-Csv exports a table of object properties and their values. Since your script is producing string objects, and the only property they have is length, that's what you got.

If you just want to save the list, use Out-File or Set-Content instead of Export-Csv.

The previous answer does work, but what if someone was looking to output it into a CSV file.


This does NOT work:

$str_list = @('Mark','Henry','John')
$str_list | Export-Csv .\ExportStrList.csv -NoType

Because Export-Csv takes Objects and outputs properties. The only properties for a String[ ] is Length, so the CSV file only contains Lengths.

To fix this we need to change the String[ ] into an Object[ ]. The simplest way is with Select-Object.


Put each String into the Name property of a new Object[ ], like this:

$str_list = @('Mark','Henry','John')
$obj_list = $str_list | Select-Object @{Name='Name';Expression={$_}}
$obj_list | Export-Csv .\ExportStrList.csv -NoType

Just to re-iterate, Select-Object outputs a custom PSObject that can easily be manipulated. This is very powerful information, use it wisely.

This worked for me:

$data = @()
$row = New-Object PSObject
$row | Add-Member -MemberType NoteProperty -Name "name1" -Value "Test"
$row | Add-Member -MemberType NoteProperty -Name "name2" -Value 2
$data += $row

$data | Export-Csv "Text.csv" -NoTypeInformation
Zane Tan
$output |Select-Object * | Export-Csv 'h:\filename.csv' -NoTypeInformation
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!