29
votes

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 fullname | % { ($_ -split '\')[7] 

But if I add | export-csv c:\test.txt then I see following in the file not the folder name I expected just like I see it on the screen.

#TYPE System.String
"Length"
"13"
"18"
"20"
"22"
"29"
"21"
"24"
"11"
"17"
"20"
"20"
6

6 Answers

34
votes

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.

23
votes

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.

8
votes

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
0
votes

This is another way to handle this issue:

  1. Out-File outputs by default

Define the master array list

$MASTER_ARRAY_LIST =  [System.Collections.ArrayList]@()

Define the output filename

$OutputFilename="C:\TEMP\MyOutputFile.csv"

ForEach ( $Something in $List_of_Somethings) {
    $CURRENT_RECORD_DETAILS = New-Object PSObject -Property @{'name'=$($Something.Name);'fullname'=$($Something.FullName);'id'=$($Something.ID)}
    $MASTER_ARRAY_LIST.Add( $CURRENT_RECORD_DETAILS ) > $null
}

$MASTER_ARRAY_LIST.ToArray() | Select-Object -Property name,fullname,id | Export-Csv -Path $OutputFilename -NoTypeInformation
0
votes
$test = @("test1","test2","test3")
$test | export-csv "firstTry.csv"
#We see that this fails. So here is how to to do it with the desired results

foreach ($item in $test) {
  [ pscustomobject]@{ ResultColumn = $item } | Export-Csv -Path ./secondTry.csv -NoTypeInformation -Append
}
-2
votes
$output |Select-Object * | Export-Csv 'h:\filename.csv' -NoTypeInformation