Question:
I am trying to format a PSObject related to a question a few days back. My object looks like this:
1 2 3 4 5 6 7 |
New-Object PSObject -Property @{ "Version"= $winVersion.Caption "Processor Name" = $processorInfo.Name "Processor Manufacturer" = $processorInfo.Manufacturer "Processor Max Clock Speed" = $processorInfo.MaxClockSpeed } |format-list |
The above gives the following output:
1 2 3 4 5 |
Processor Manufacturer : GenuineIntel Processor Max Clock Speed : 2201 Version : Microsoft Windows 8 Pro Processor Name : Intel(R) Core(TM) i7-2670QM CPU @ 2.20GHz |
However, this:
1 2 3 4 5 6 7 |
New-Object PSObject -Property @{ "Windows Version"= $winVersion.Caption "Processor Name" = $processorInfo.Name "Processor Manufacturer" = $processorInfo.Manufacturer "Processor Max Clock Speed" = $processorInfo.MaxClockSpeed } |format-list |
gives the following output:
1 2 3 4 5 |
Processor Manufacturer : GenuineIntel Processor Max Clock Speed : 2201 Processor Name : Intel(R) Core(TM) i7-2670QM CPU @ 2.20GHz Windows Version : Microsoft Windows 8 Pro |
Not really a big deal, but I wonder why the formatting changes? It does not seem to be alphabetical in any way. Furthermore, I tried sorting the object with Sort-Object (from A-Z) but to no avail. Is it String related?
Answer:
The order of a hashtable
can’t be predicted (in PowerShell V3.0 you can user the [ordered]
accelerator to make an hashtable ordered), but in V2.0 you need to build your custom object like this to preserve properties order:
1 2 3 4 5 6 7 8 |
$o = New-Object PSObject $o | add-member Noteproperty "Version" $winVersion.Caption $o | add-member Noteproperty "Processor Name" $processorInfo.Name $o | add-member Noteproperty "Processor Manufacturer" $processorInfo.Manufacturer $o | add-member Noteproperty "Processor Max Clock Speed" $processorInfo.MaxClockSpeed $o | format-list |