Colyn1337
Colyn1337

Reputation: 1723

How do You Control Column Name Position When Creating CSV Exportable Object Arrays?

REFERENCE SCRIPTS:

Script 1:

$csvList = @()

$csvList += New-Object PSObject -Property @{name="test1";accountname="testuser1";mail="[email protected]"}
$csvList += New-Object PSObject -Property @{name="test2";accountname="testuser2";mail="[email protected]"}
$csvList += New-Object PSObject -Property @{name="test3";accountname="testuser3";mail="[email protected]"}
$csvList += New-Object PSObject -Property @{name="test4";accountname="testuser4";mail="[email protected]"}

$csvList | Export-Csv c:\temp\testcsv.csv -NoTypeInformation

Script 2 (added in edit to reflect extended usage):

$aTest = @()

for($x=0;$x -le 5;$x++)
{
    $aTest += New-Object PSObject -Property @{Name="test$($x)"; `
                                              AccountName="testuser$($x)"; `
                                              Mail="user$($x)@somewhere.com"}
}

$aTest | Export-Csv c:\temp\testcsv.csv -NoTypeInformation

QUESTION:

While that script creates my CSV and includes all the data I need in the correct rows, I cannot figure out how to control column position. Even though I'm ordering and adding the data by name,accountname,mail Powershell orders it by mail,name,accountname. How can I control the column order?

Note: If I do a screen dump of the contents of $csvList before the export the order has already been changed.

Upvotes: 3

Views: 4480

Answers (2)

mjolinor
mjolinor

Reputation: 68273

If you're running V4, they added a type accelerator ([PSCustomObject]) for creating PS Objects that uses an ordered hash table so the properties stay in the order they were declared in the hash literal.

$(
[PSCustomObject]@{name="test1";accountname="testuser1";mail="[email protected]"}
[PSCustomObject]@{name="test2";accountname="testuser2";mail="[email protected]"}
[PSCustomObject]@{name="test3";accountname="testuser3";mail="[email protected]"}
[PSCustomObject]@{name="test4";accountname="testuser4";mail="[email protected]"}
) | Export-Csv c:\temp\testcsv.csv -NoTypeInformation

Edit: Example using a loop to build up an ordered hash table:

foreach ($i in 1..4)
 {
   $ht = [ordered]@{}
   $ht.name = "test$i"
   $ht.accountname = "testuser$i"
   $ht.mail = "[email protected]"
   [PSCustomObject] $ht
 }

Upvotes: 3

Ross Presser
Ross Presser

Reputation: 6255

Each PSObject is essentially a hashtable. There is no ordering of values in a hashtable. Select-Object can reformat the order for you. Make your last line:

 $csvList | Select-Object name,accountname,mail | Export-Csv c:\temp\testcsv2.csv -NoTypeInformation

Got the idea from this forum question: Source

Upvotes: 3

Related Questions