Active Directory Friday: Distribution group membership for AD User

To get a list of distribution groups an Active Directory user account is a member of of we can query Active Directory. For example by combining the Get-ADUser and Get-ADGroup cmdlets. To generate this list the following code can be used:

1
2
3
Get-ADUser -Identity JaapBrasser -property memberof |
Select-Object -ExpandProperty memberof | Get-ADGroup |
Where-Object {$_.groupcategory -eq 'Distribution'}

The Get-ADUser cmdlet gets all the groups Jaap Brasser is a member of, the Select-Object cmdlet expands the MemberOf attribute which is then piped into the Get-ADGroup cmdlet. The last step is using the Where-Object cmdlet to filter out only the Distribution groups to get the desired results.

Alternatively the DirectoryServices DirectorySearcher object can be used. This object does not require the Active Directory module to be installed and can run on any version of PowerShell. The following code can be used:

1
2
3
4
5
6
7
8
9
10
$ADSearcher = New-Object DirectoryServices.DirectorySearcher -Property @{
    Filter = "(samaccountname=JaapBrasser)"
} | ForEach-Object {
    $_.FindOne().Properties.memberof | ForEach-Object {
        $CurrentGroup = [adsi]"LDAP://$_"
        if (-not ([int](-join $CurrentGroup.Properties.grouptype) -band 0x80000000)) {
            $CurrentGroup.Properties.name
        }
    }
}

This sample works by querying Active Directory for the samaccountname JaapBrasser. Of this user account the distinguishedname of each group object is retrieved. The group type is explained in last weeks post as well, in which I explained about the hex codes which defines whether a group is a Security Group or a Distribution group. The article is available here: Creating Active Directory groups using PowerShell

For more information on this subject please refer to the following links:

Distribution group membership
Get-ADGroup
Get-ADUser
Understanding Groups
2.2.12 Group Type Flags
Creating Active Directory groups using PowerShell
Share

Leave a Reply

Your email address will not be published.