Export-CSV exports length but not name

前端 未结 5 1272
迷失自我
迷失自我 2020-11-28 12:23

I have this code that I am running from powershell. When I run it without the export-csv i get all the folder names on the screen.

dir | select -expand fulln         


        
5条回答
  •  心在旅途
    2020-11-28 13:20

    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.

提交回复
热议问题