Sorting AD objects

Tagged: 

This topic contains 1 reply, has 2 voices, and was last updated by Profile photo of Rob Simmers Rob Simmers 1 month ago.

  • Author
    Posts
  • #65230
    Profile photo of Greg Martin
    Greg Martin
    Participant

    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?

  • #65238
    Profile photo of Rob Simmers
    Rob Simmers
    Participant

    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.