Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

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 }


This post first appeared on Hinchley.net, please read the originial post: here

Share the post

Sort an array of hashes using multiple keys in PowerShell

×

Subscribe to Hinchley.net

Get updates delivered right to your inbox!

Thank you for your subscription

×