Sorting AD objects

Welcome Forums General PowerShell Q&A Sorting AD objects

This topic contains 1 reply, has 2 voices, and was last updated by

 
Participant
1 year, 8 months ago.

  • Author
    Posts
  • #65230

    Participant
    Points: 0
    Rank: Member

    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

    Participant
    Points: 30
    Rank: Member

    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
    

The topic ‘Sorting AD objects’ is closed to new replies.