Get a sorted list of AD Group Members with Powershell

Here's a way to get a sorted list of AD users from a security group.  The trick of this is that Get-AdGroupMember returns and AdPrinciple, not an AdUser.  The principle can be a user, group or computer and does not contain the surname and givenname fields, because they are not relevant to all of the objects.

We can use the Get-AdUser to fetch the name fields that we want to sort by, but get-aduser does not accept pipeline input, so you have to use a foreach loop to fetch each user .  Declaring the variable at the top as a powershell array with " = @()" allows us to insert each object into the array.

Finally, we can sort the results with sort-object:

$users = @()

foreach($user in  Get-ADGroupMember -Server <MyServer> "<MyAdGroup>")
    $users += get-aduser -Server <MyServer> $user.SamAccountName

$users | sort-object Surname | format-table -AutoSize SurName, GivenName