Share via


Convert data in CSV format using custom labels in PowerShell

When we export any variables without properties using export-csv, we don't get the actual data in the csv file. we only get Length of each values in the variable as shown below. 

I create a variable $array 

$array = "tom","Dick","Harry"

Then try to export it to csv file 

$Array |export-csv Array,csv -notypeinformation 

I get below output 

Length
3
4
5

To fix this, I will have to create a property using custom labels. But before that I would like to explain why it didn't export the actual values. 

$array contains only one property i.e. Length. You can check the same by typing  $array|gm -MemberType Properties.  You will get below result. 

   TypeName: System.String

Name   MemberType Definition       
----   ---------- ----------       
Length Property   int Length {get;}

As the values "tom","Dick","Harry" don't have any property name. they will not be exported to .csv file.  Use below cmdlet to create a property. 

$ArrayWithProp = $array |select @{n="Name";e={$_}}

Now type $ArrayWithProp |gm  -MemberType Properties to check the properties.  You will get the property "Name"

TypeName: Selected.System.String

Name MemberType   Definition            
---- ----------   ----------            
Name NoteProperty System.String Name=tom

now  export the variable to csv using below cmdlet.

$ArrayWithProp |export-csv Array,csv -notypeinformation 

You will get below output! 

Name
tom
Dick
Harry