Search code examples
powershelladsi

ADSI Search for DistinguishedName of the primary group based on primarygroupid


Because we don't have the active directory module available on all our systems we're using ADSI instead. The following code retrieves a user object from AD by using the AdsiSearcher:

$ADUser = ([AdsiSearcher]"(samaccountname=$SamAccountName)").FindOne()

This results in finding the property primarygroupid which represents the domain primary group for user, usually number 513. When we have this number we would like to find the distinguishedName of the group. However, the code below does that just fine I was wondering if there is a better filter that can be used instead of filtering after the FindAll() method?

    $searcher = [adsisearcher]'objectclass=group'
    $searcher.PropertiesToLoad.Add('primarygrouptoken')
    $searcher.PropertiesToLoad.Add('distinguishedName')
    $searcher.FindAll() |
    Where-Object { $_.Properties.primarygrouptoken -eq 513}

Something like this would be great but it's not possible:

([adsisearcher]”(&(objectCategory=group)(primaryGroupid=513))”).FindOne()

Solution

  • The primaryGroupToken is a constructed attribute, meaning that it's not actually materialized in the database, and can't be filtered using LDAP.

    In order to build an equivalent filter we'll need to look at how it is constructed - and the primary group token in Active Directory is always the same as the group's RID part (the relative identifier) of the objectSid attribute.

    So, if we want to search by it, we can simply filter by objectSid instead:

    # Obtain domain SID
    $dncDN = ([adsi]"LDAP://RootDSE").defaultNamingContext
    $dnc = [adsi]"LDAP://$dncDN"
    $domainSID = [System.Security.Principal.SecurityIdentifier]::new($dnc.objectSid.Value, 0)
    
    # Set the group ID we're looking for
    $RID = 513
    
    # Search for group by objectSid value:
    ([adsisearcher]"(&(objectCategory=group)(objectSid=${domainSID}-${RID}))").FindOne()