PowerShell – Keep Order of Properties in Custom PS Objects

In PowerShell, we use PSObject and Hashtable to keep and control a set of properties and values as custom objects. Sometimes, you may face a problem in displaying properties in the same order as we set in the object. You could randomly face the same problem while exporting data from an array of custom ps objects using Export-CSV command.

Problem

The following commands create a custom ps object array and keep the output in $Result variable.

$Result=@() 
1..5 | ForEach {
$HTProps = @{ 
Prop1 = 'Value'+$_+'1'
Prop2 = 'Value'+$_+'2'
Prop3 = 'Value'+$_+'3'
}
$Result += New-Object -TypeName PSObject -Property $HTProps
}

When you try to display the object values using the below command, you may not get the properties in the correct order.

PS C:\> $Result

Prop2   Prop1   Prop3
-----   -----   -----
Value12 Value11 Value13
Value22 Value21 Value23
Value32 Value31 Value33

You will face the same in the Export command.

$Result | Export-CSV "C:\Test.csv" -NoTypeInformation -Encoding UTF8

Solution – Preserve using [ordered] accelerator

We can use the [ordered] type accelerator with property hash table to preserve the order.

$Result=@() 
1..5 | ForEach {
$HTProps = [ordered]@{ 
Prop1 = 'Value'+$_+'1'
Prop2 = 'Value'+$_+'2'
Prop3 = 'Value'+$_+'3'
}
$Result += New-Object -TypeName PSObject -Property $HTProps
}

Now, you can select and export the object properties in same order.

PS C:\> $Result

Prop1   Prop2   Prop3
-----   -----   -----
Value11 Value12 Value13
Value21 Value22 Value23
Value31 Value32 Value33
Advertisement