Sorting AD objects

I hope you don’t mind, but I’m going to ask and answer a question here. However, I’d like to see alternate approaches.

I’m dumping a list of user accounts from AD and I’d like to sort them by OU. The DN lists the cn first which screws this up as a sorting key without modification. After some poking around, I realized canonical name has exactly what I need. It lists the object location in the form of:

example.com/city/User Accounts/yramos

Any better ways to accomplish this?

You could parse out the OU and then Sort on OU and SamAccountName (or whatever name field you wanted to use):

$users = Get-ADUser -Filter *
$users = $users | Select *, @{Name="OU";Expression={($_.DistinguishedName -split ",")[1].Replace("OU=","")}}
$users | Sort-Object -Property OU, SamAccountName