Thursday, November 22, 2012

LDAP AD: Finding members of a group who have it as their primary group

An interesting problem came up today, where a developer was having problems pulling members of a domain group. The group shows hundreds of users when looking at it in Active Directory Users and Computers, however any LDAP connection to it only results in 50 users. Based on the name, I realized this group was used as a "Primary Group" for a group of special case users. Typically the "Primary Group" for a user is the Domain Users builtin group for the domain. If you look at this forum post, it shows a way to query for this group. On each user account is an attribute called PrimaryGroupID, which is a numeric value. In the article you can see that Domain Users is value 513 which is derived from its well known SID, ending in -513. So if you have another group that you want to look at, you will need to pull its SID, strip off the last number and query for all users that have that PrimaryGroupID number. This may not yield a complete list, so you can also search memberOf for that same group, or go with the member's attribute of the group itself. The first option allows you to build a single query with an | (or) statement in it, the latter would require some combining.

As an example, lets say our group was called SecondaryUsers.

In powershell we can get the object SID
$id = new-object System.Security.Principal.NTAccount(CONTOSO\SecondaryUsers)
$sid = $id.translate([]).tostring()
$sidval = $sid.substring($sid.lastindexof('-')+1)

Now that we have our group's number, lets do an ldap search

$de = new-object directoryservices.directoryentry("LDAP://dc=contoso,dc=com")
$ds = new-object directoryservices.directorysearcher($de)
$ds.filter = "(&(objectclass=user)(|(primarygroupid=$($sidval))(memberof:=cn=SecondaryUsers,ou=MyGroups,dc=Contoso,Dc=com)))"
$ds.propertiestoload.add("samaccountname") |out-null
$users = $ds.findall()

Now we have all of the users under that group, whether they are memberof or member by PrimaryGroup.

No comments:

Post a Comment