PowerShell - Control What Order Properties Are Displayed On A Custom Objects And...

 1 year ago
source link: https://thomasrayner.ca/powershell-control-what-order-properties-are-displayed-on-a-custom-objects-and-hash-tables/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

PowerShell - Control What Order Properties Are Displayed On A Custom Objects And Hash Tables

There are a handful of different ways to create custom objects in PowerShell, including building one from a hash table. You might do something like this.

PS> $props = @{'prop1' = 1; 'prop2' = 2}
PS> $obj = New-Object -TypeName PSObject -Property $props

But then, just run $obj and see what you get. This is what I got.

PS> $obj

prop2 prop1
----- -----
    2     1

It put prop2 before prop1 even though I put prop1 first in the hash table! Most of the time, this doesn’t matter, but what about when it does?

Sure, you could use Select-Object to accomplish this.

PS> $obj | Select-Object -Property prop1,prop2

prop1 prop2
----- -----
    1     2

But that seems excessively verbose and inefficient. Luckily there is a better way. Introducing Ordered Hash Tables!

Ordered hash tables are pretty much what they sound like. By default, a hash table is a collection of objects (key and value pairs) whose order isn’t important. An ordered hash table is the same thing, but where the order they are in the hash table matters, and they’re pretty easy to use. Our first lines of code from this example becomes this.

PS> $props = [ordered]@{'prop1' = 1; 'prop2' = 2}
PS> $obj = New-Object -TypeName PSObject -Property $props

Just add the [ordered]  accelerator to the hash table, and now PowerShell will respect the order that you enter items into your hash table.

Written on January 24, 2018

About Joyk

Aggregate valuable and interesting links.
Joyk means Joy of geeK