1

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()
DarkLite1
  • 13,637
  • 40
  • 117
  • 214
  • Possible duplicate of [Issue with trying to pass variable into \[adsisearcher\]](https://stackoverflow.com/questions/27623958/issue-with-trying-to-pass-variable-into-adsisearcher) – Theo Oct 22 '19 at 10:58
  • It's not related as I am looking to filter on the property that contains the number `513`. I am well aware of how to use variables just not if it's possible to filter on this property. – DarkLite1 Oct 22 '19 at 11:10

1 Answers1

2

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()
Mathias R. Jessen
  • 157,619
  • 12
  • 148
  • 206
  • Thank you Mathias this was exactly what I was looking for. I already found it strange to use `FindAll()` as it takes longer than `FindOne()` and was unnecessary in this case. – DarkLite1 Oct 23 '19 at 06:46