Sorting AD objects

This topic contains 1 reply, has 2 voices, and was last updated by  Rob Simmers 1 year, 4 months ago.

  • Author
  • #65230

    Greg Martin

    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: Accounts/yramos

    Any better ways to accomplish this?

  • #65238

    Rob Simmers

    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

You must be logged in to reply to this topic.