Your strategic advantage starts here

Export Data to a CSV and Maintain the Column Order

Export Data to a CSV and Maintain the Column Order

This post provides a simple example of how we can export data to a CSV and maintain the column order:

 $csvFile = "c:\temp\alkane.csv"

 $exampledata = @(@("John","37"),@("Peter","14"),@("Michelle","22"),@("Abdul","31"),@("Roger","22"),@("Rachel","50"))
 $csvwrapper = @()

foreach($person in  $exampledata) {
    $name = $person[0]
    $age = $person[1]    
    
    #append to a wrapper which we export to CSV at the end (Name and Age are the column names we want in the CSV)
    $csvwrapper += New-Object PSObject -Property @{ 
        Name = $name;
        Age = $age; 
    }
}

 $csvwrapper | 
 Select Name, Age | #we pipe our wrapper into this so we can define the order we want our columns to display in the CSV
 Export-Csv -Path $csvFile -NoTypeInformation
Related Posts
Leave a Reply
Give us a call

Available from 9am to 8pm, Monday to Friday.

Send us a message

Send your message any time you want.

Our usual reply time: 1 Business day
Give us a call

Available from 9am to 8pm, Monday to Friday.

Send us a message

Send your message any time you want.

Our usual reply time: 1 Business day