Powershell – Getting list of users indirectly members of an AD group through LDAP

active-directoryldappowershell

I'm having a bit of a problem with LDAP search that should specify whether a user is a member of a given AD group or not (recursively).

Basically, what I'm doing is issue a LDAP search with the following parameters:

get-aduser -LDAPFilter "(memberof:1.2.840.113556.1.4.1941:={group LDAP path})" -SearchBase "{AD LDAP base}"

This does yield the expected result: instead of getting all users who are directly or indirectly members of the group I'm searching for, I get all direct members of that group, plus a random selection of indirect members (members of groups that are member of the searched for group).

The list I'm getting seems arbitrary: I can't find any difference in group membership between two users who should be present in the result set but one is there and the other isn't.

(I need to solve this issue with LDAP search because the result will be used in an application, not through powershell. But using powershell in this way, I can reproduce the original problem in the way described).

Best Answer

Use Get-ADGroupMember with the -Recursive switch to get a listing of all members that do not contain child objects. This will dive down into members that have child object to get their members.

Example

$groupName = "Domain Admins"
$group = Get-ADGroup $groupName
$groupMembers = Get-ADGroupMember $group -Recursive

You need to query the group instead of the users because memberOf can give inconsistent results due to users being members of nested groups / roles / etc.