PowerShell Script to Get Users in Group
Get-ADGroupMember -Identity 'GroupName' -Recursive | Where-Object { $_.objectClass -eq 'user' } to get all users in a group in PowerShell.Examples
How to Think About It
Algorithm
Code
Import-Module ActiveDirectory $groupName = 'YourGroupName' $users = Get-ADGroupMember -Identity $groupName -Recursive | Where-Object { $_.objectClass -eq 'user' } $users | ForEach-Object { Write-Output $_.Name }
Dry Run
Let's trace getting users from group 'ITSupport' through the code
Set group name
$groupName = 'ITSupport'
Get all group members
Get-ADGroupMember returns 3 members: Jane Smith (user), Mark Lee (user), SupportGroup (group)
Filter only users
Keep Jane Smith and Mark Lee, remove SupportGroup
| Member Name | ObjectClass | Included? |
|---|---|---|
| Jane Smith | user | Yes |
| Mark Lee | user | Yes |
| SupportGroup | group | No |
Why This Works
Step 1: Import Active Directory module
The Import-Module ActiveDirectory command loads the tools needed to query AD groups.
Step 2: Get group members recursively
Get-ADGroupMember -Recursive fetches all members including those in nested groups.
Step 3: Filter users only
Using Where-Object { $_.objectClass -eq 'user' } keeps only user accounts, excluding groups or computers.
Alternative Approaches
Import-Module ActiveDirectory $groupName = 'YourGroupName' $users = Get-ADGroupMember -Identity $groupName | Where-Object { $_.objectClass -eq 'user' } $users | ForEach-Object { Write-Output $_.Name }
$group = [ADSI]("LDAP://CN=YourGroupName,OU=Groups,DC=domain,DC=com") $members = $group.member | ForEach-Object { [ADSI]"LDAP://$_" } $users = $members | Where-Object { $_.objectClass -eq 'user' } $users | ForEach-Object { $_.Name }
Complexity: O(n) time, O(n) space
Time Complexity
The script queries all members of the group, so time grows linearly with the number of members (n). Filtering is also linear.
Space Complexity
The script stores all group members in memory, so space grows linearly with n.
Which Approach is Fastest?
Using Get-ADGroupMember -Recursive is efficient and simple. ADSI method is slower and more complex.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Get-ADGroupMember -Recursive | O(n) | O(n) | Complete user list including nested groups |
| Get-ADGroupMember (no recursion) | O(n) | O(n) | Simple groups without nested members |
| ADSI Query | O(n) | O(n) | Environments without Active Directory module |
-Recursive with Get-ADGroupMember to include users in nested groups.objectClass -eq 'user' and getting groups or computers in the output.