Sorting Multiple Properties in a Object in PowerShell

Viewed 663

I'm trying to sort both columns of my variable, however, for the life of me I can't seem to get it to work.

Here is my example CSV data:

Department                Users
---                      ---
Human Resources           Wendell
IT                        John
IT                        Ashley
Human Resources           Blake
IT                        Peter
Human Resources           Amber

This is what I have so far.

$OrgUsers = Import-Csv OrgUsers.csv

$OrgUsers | Group-Object Department | @{Name='Department';Expression='Name'},@{Name='Users';Expression={ @($_.Group.Users) }}

The output from the above looks like:

Department                User
---                      ---
Human Resources          {Wendell, Blake, Amber}
IT                       {John, Ashley, Peter}

I'm trying to sort both columns which should be relatively simple I thought.

This is what I have tried so far - this works on the 2nd column and sorts the users alphabetically

$OrgUsers | Group-Object Department | Select-Object @{Name='Department';Expression='Name'},@{Name='Users';Expression={ @($_.Group.Users) }} | Sort-Object @{Expression={$_.Users};Ascending=$true}

But when I try to do both properties, it will only sort the first column and not the second.

$OrgUsers | Group-Object Department | Select-Object @{Name='Department';Expression='Name'},@{Name='Users';Expression={ @($_.Group.Users) }} | Sort-Object @{Expression={$_.Department};Ascending=$true},@{Expression={$_.Users};Ascending=$true}

I would like my end result to look like:

Department                User
---                      ---
IT                       {Ashley, John, Peter}
Human Resources          {Amber, Blake, Wendell}

Any help would be greatly appreciated, thanks!

1 Answers

What is happening is you trying to first sort on department and then on users which is a single array (containing multiple names). Since there is only a single line per department it is already sorted.

 Department                User
---                      ---
IT                       {Ashley, John, Peter} # Only 1 line exists for IT Department; cannot be sorted by other columns

Human Resources          {Amber, Blake, Wendell} # Only 1 line exists for IT Department; cannot be sorted by other columns

You can instead sort the user arrays separately. You can do this in the calculated property where you are assigning the user arrays.

$OrgUsers |
    Group-Object Department |
    Sort-Object Name |
    Select-Object @{Name = 'Department'; Expression = 'Name' },
                  @{Name = 'Users'; Expression = { $_.Group.User | Sort-Object } } 
Related