🎓 A1Learner
🔍
0 of 52 lessons completed

PowerShell Ordered Hashtables

An ordered hashtable stores key and value pairs in the order you wrote them. That order stays fixed when you read the keys or values back.

Read the keys in order

Keys lists the keys in the order they were written. Join prints them on one line.

$book = [ordered]@{title = "Dune"; author = "Frank Herbert"; year = 1965}
$book.Keys -join ", "

Read the values in order

Values lines up with the keys. The first value belongs to the first key, and so on.

$book = [ordered]@{title = "Dune"; author = "Frank Herbert"; year = 1965}
$book.Values -join ", "

Order is insertion order, not alphabetical order

The keys stay in the order they were written, even when that order is not alphabetical.

$oh = [ordered]@{b = 2; a = 1; c = 3}
$oh.Keys -join ", "

Example

$person = [ordered]@{name = "Ana"; city = "Lisbon"; age = 31}
$person.Keys -join ", "
$person.Values -join ", "

Key points

  • Hashtable: a set of key and value pairs, where each key names its value.
  • Ordered hashtable: a hashtable that keeps its keys in the order they were written.
  • Use [ordered]@{} to build an ordered hashtable, with semicolons between the pairs.
  • Keys: a property that lists the keys in their stored order.
  • Values: a property that lists the values in the same order as their keys.
  • Join the keys or values to print them on one line in order.

In this example, an ordered hashtable holds a name, a city, and an age. The keys print first in the order they were written, and then the values print in that same order.

Note

a plain hashtable does not keep key order, so use [ordered]@{} whenever order matters.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does ([ordered]@{b = 2; a = 1}).Keys -join ", " print?