Why would I use an ordered hash in Powershell?

  • A+

I'm reading a tutorial and learned that Powershell supports ordered hashes. When would I use that feature?

Sample of what I'm talking about:

$hash = [ordered]@{ ID = 1; Shape = "Square"; Color = "Blue"} 


The reason for an ordered dictionary is for display / typecast purposes. For example, if you want to cast your hashtable to a pscustomobject and you want your keys to be in the order you enter them, you use ordered. The use-case here is when you use Export-Csv, the headers are in the right order. This is just one example I could think of off the top of my head. By design, the hashtable type doesn't care about the order you enter keys/values and will be different each time you display it to the success stream.

An additional use-case for the ordered dictionary: you can treat your hashtable as an array and use numerical accessors to find items, such as $myOrderedHash[-1] will grab the last item added to the dictionary.


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: