How to Get AD Group Members with PowerShell Using Get-ADGroupMember

Get-ADGroupMember Powershell

Active Directory (AD) represents the backbone of user and resource management for system administrators managing Windows environments. Efficiently retrieving and analyzing group memberships is a critical task that can significantly streamline administrative workflows. PowerShell, Microsoft’s powerful automation framework, offers the Get-ADGroupMember cmdlet specifically designed to address this need.

This comprehensive guide explores how to leverage the Get-ADGroupMember cmdlet to its fullest potential, enabling you to extract, filter, and manipulate AD group membership data precisely and efficiently.

Understanding Get-ADGroupMember Fundamentals

The Get-ADGroupMember cmdlet is part of the Active Directory module for PowerShell. This cmdlet provides a straightforward method to retrieve all members from a specified Active Directory group, offering various parameters to customize your query.

Basic Syntax

Get-ADGroupMember [-Identity] <ADGroup> [[-Server] <String>] [-Credential <PSCredential>] 
                 [-Partition <String>] [-Recursive] [-AuthType <ADAuthType>] [<CommonParameters>]

Key Parameters Explained

  • Identity: Specifies the Active Directory group to query. You can use any of these formats:
  • Distinguished Name (DN)
  • GUID
  • Security Identifier (SID)
  • Security Accounts Manager (SAM) account name
  • Recursive: When specified, retrieves all members from the entire hierarchy of nested groups, not just direct members.
  • Server: Allows you to target a specific Active Directory Domain Services instance by providing either a domain name or a directory server address.
  • Credential: Enables the use of alternative credentials when running the cmdlet.
  • Partition: Specifies the distinguished name of an Active Directory partition to search.
  • AuthType: Specifies the authentication method for connecting to the AD server.

Practical Examples for Everyday Administration

Example 1: Retrieving and Sorting Basic Group Membership

To retrieve a sorted list of members from an AD group:

Get-ADGroupMember -Identity "Marketing_Team" | Select-Object Name | Sort-Object Name

This command:

  1. Retrieves all members of the “Marketing_Team” group
  2. Selects only the Name property for each member
  3. Sorts the results alphabetically by name

The output provides a clean, alphabetical list of all group members:

Name
----
Andrew Johnson
Emily Parker
Marketing_APAC
Marketing_EMEA
Sarah Williams

Example 2: Extracting User Information from Nested Groups

To retrieve detailed user information from both a group and its nested subgroups:

Get-ADGroupMember -Identity "Corporate_Access" -Recursive | 
    Get-ADUser -Property DisplayName, Department, Title, EmailAddress | 
    Select-Object DisplayName, Department, Title, EmailAddress |
    Sort-Object Department, DisplayName |
    Format-Table -AutoSize

This advanced query:

  1. Retrieves all members (including those in nested groups) from “Corporate_Access.”
  2. Processes each member through Get-ADUser to extract additional properties
  3. Selects relevant user attributes for display
  4. Sorts results by department and then by display name
  5. Formats the output as a table with optimized column widths

Example 3: Identifying Enabled User Accounts Within a Group

When you need to audit active accounts within a group:

$groupName = "Finance_Approvers"

$groupMembers = Get-ADGroupMember -Identity $groupName | Where-Object {$_.objectClass -eq "user"}

foreach ($member in $groupMembers) { 
    Get-ADUser -Identity $member -Properties Name, SamAccountName, UserPrincipalName, Enabled, LastLogonDate | 
        Where-Object {$_.Enabled -eq $true} | 
        Select-Object Name, SamAccountName, UserPrincipalName, Enabled, LastLogonDate
}

This script:

  1. Defines the target group name
  2. Retrieves all members that are user objects (excluding nested groups)
  3. Processes each user to check their account status
  4. Returns detailed information about enabled accounts only, including their last logon date

Advanced Filtering Techniques

Filtering by Object Class

To separate users from groups in your results:

# Get only user objects from the group
Get-ADGroupMember "IT_Support" | Where-Object {$_.objectClass -eq "user"} | 
    Select-Object Name, SamAccountName, DistinguishedName | 
    Format-Table -AutoSize

# Get only group objects (nested groups)
Get-ADGroupMember "IT_Support" | Where-Object {$_.objectClass -eq "group"} | 
    Select-Object Name, DistinguishedName | 
    Format-Table -AutoSize

Creating Custom Reports

For comprehensive reporting, you can combine multiple cmdlets:

Get-ADGroupMember -Identity "VPN_Access" -Recursive | 
    Get-ADUser -Properties DisplayName, Title, Department, Manager, LastLogonDate |
    ForEach-Object {
        $managerInfo = Get-ADUser -Identity $_.Manager -Properties DisplayName

        [PSCustomObject]@{
            "Name" = $_.DisplayName
            "Title" = $_.Title
            "Department" = $_.Department
            "Manager" = $managerInfo.DisplayName
            "Last Logon" = $_.LastLogonDate
        }
    } |
    Export-Csv -Path "VPN_Access_Report.csv" -NoTypeInformation

This advanced script:

  1. Gets all members of the VPN_Access group, including those in nested groups
  2. Retrieves extended properties for each user
  3. Looks up the manager’s display name for each user
  4. Creates custom objects with formatted information
  5. Exports the results to a CSV file for further analysis

Overcoming Common Limitations

Exceeding the 5000-Member Query Limit

By default, Get-ADGroupMember has a limit of retrieving 5,000 objects. When dealing with large groups, you might encounter the error:

Get-ADGroupMember: The size limit for this request was exceeded.

To resolve this limitation:

  1. On your Domain Controller, navigate to C:\Windows\ADWS
  2. Create a backup of the file Microsoft.ActiveDirectory.WebServices.exe.config
  3. Open the file with a text editor
  4. Look for the MaxGroupOrMemberEntries key
  5. If it exists, increase its value; if not, add the following line:
   <add key="MaxGroupOrMemberEntries" value="10000"/>
  1. Save the file and restart the Active Directory Web Services

Important Note: Always back up configuration files before modification, and test changes in a non-production environment first.

Optimizing Performance for Large Groups

When dealing with groups containing thousands of members, consider these optimization techniques:

# Use Get-ADGroup with -Properties Members instead
$largeGroup = Get-ADGroup -Identity "All_Employees" -Properties Members
$memberCount = $largeGroup.Members.Count
Write-Host "The group contains $memberCount members"

# Process in smaller batches if needed
$largeGroup.Members | 
    Select-Object -First 1000 | 
    ForEach-Object {
        $member = Get-ADObject -Identity $_
        # Process each member...
    }

Best Practices and Advanced Tips

Security Considerations

When running scripts that access Active Directory:

  1. Use the principle of least privilege – run with accounts that have only the necessary permissions
  2. Consider using parameter validation in your scripts to prevent injection attacks
  3. Be cautious when storing credentials in scripts; use secure credential objects when necessary

Integration with Other PowerShell Commands

Combine Get-ADGroupMember with other commands for advanced functionality:

# Compare members of two groups
$group1Members = Get-ADGroupMember -Identity "IT_Access" | Select-Object -ExpandProperty DistinguishedName
$group2Members = Get-ADGroupMember -Identity "DevOps_Access" | Select-Object -ExpandProperty DistinguishedName

$onlyInGroup1 = Compare-Object -ReferenceObject $group1Members -DifferenceObject $group2Members -IncludeEqual | 
    Where-Object {$_.SideIndicator -eq "<="}

$onlyInGroup2 = Compare-Object -ReferenceObject $group1Members -DifferenceObject $group2Members -IncludeEqual | 
    Where-Object {$_.SideIndicator -eq "=>"}

$inBothGroups = Compare-Object -ReferenceObject $group1Members -DifferenceObject $group2Members -IncludeEqual | 
    Where-Object {$_.SideIndicator -eq "=="}

Creating Reusable Functions

For repeated tasks, create custom functions:

function Get-ADGroupMemberDetails {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $true)]
        [string]$GroupName,

        [switch]$IncludeNestedGroups,

        [string[]]$Properties = @("Name", "SamAccountName", "Enabled", "LastLogonDate")
    )

    $recursiveParam = @{}
    if ($IncludeNestedGroups) {
        $recursiveParam = @{Recursive = $true}
    }

    Get-ADGroupMember -Identity $GroupName @recursiveParam | 
        Where-Object {$_.objectClass -eq "user"} |
        Get-ADUser -Properties $Properties |
        Select-Object $Properties
}

# Usage
Get-ADGroupMemberDetails -GroupName "Finance_Team" -IncludeNestedGroups -Properties Name, Department, Title, EmailAddress

The Get-ADGroupMember cmdlet offers powerful capabilities for retrieving and analyzing Active Directory group membership information. By mastering this cmdlet and combining it with other PowerShell commands, system administrators can significantly enhance their ability to efficiently manage and report on AD groups.

Whether you’re conducting routine audits, generating compliance reports, or troubleshooting access issues, the techniques described in this guide provide a solid foundation for automated Active Directory management using PowerShell.

For more advanced Active Directory management, consider exploring additional PowerShell cmdlets like Set-ADGroup for modifying group attributes, Export-Csv for exporting membership data and the complete Active Directory PowerShell commands suite available in modern Windows environments.