Peter Hinchley

Learning in Public

✪ Sort an Array of Hashes Using Multiple Keys in PowerShell

A quick tip on sorting an array of hashes in PowerShell using multiple keys. Let's say you have an array, where each element is a hash containing a person's name and age:

$people = @(
  @{'name' = 'sam'; 'age' = 19},
  @{'name' = 'bob'; 'age' = 21},
  @{'name' = 'bob'; 'age' = 19}
)

Now you want to sort the array of people by name. And when multiple people share the same name, you want to perform a secondary sort by age. Try this:

$people | sort { $_.name }, { [int]$_.age }

The output:

@(
  @{'name' = 'bob'; 'age' = 19},
  @{'name' = 'bob'; 'age' = 21},
  @{'name' = 'sam'; 'age' = 19}
)

And for bonus points, if you want to sort by name in ascending order, but by age in descending order, just negate the age:

$people | sort { $_.name }, { ! [int]$_.age }