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.

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

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.

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.

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

 

Leave a Reply

Your email address will not be published. Required fields are marked *