Query PrincipalSearcher for containing multiple strings

1.8k views Asked by At

I want to be able to query the active directory give a list of all groups containing certain words like Users or Administrators below is what i've got so far

PrincipalContext ctx = new PrincipalContext(ContextType.Domain);
GroupPrincipal qbeGroup = new GroupPrincipal(ctx);
qbeGroup.DisplayName = "Administrators";
qbeGroup.DisplayName = "Users";
PrincipalSearcher srch = new PrincipalSearcher(qbeGroup);
return srch.FindAll().Select(g => g.Name).ToArray();

This code doesn't even seem to filter out the the Group names that is not Administrators or Users. But anyway what I can't figure out is how to query if the group name contains? and not if group name is equal to and how to do this of multiple strings.

I can do the same thing using DirectoryEntry so I put it here for referance

var groups = new List<string>();
var path = string.Format("LDAP://CN=Users,DC=company,DC=com");
var computerEntry = new DirectoryEntry(path);

if (computerEntry != null)
   {
       using (computerEntry)
       {
            var userNames =
            from DirectoryEntry childEntry
            in computerEntry.Children
            where childEntry.SchemaClassName == "Group"
            select childEntry.Name;
            foreach (var name in userNames)
            {
                 if (name.Contains("Administrators") || name.Contains("Users"))
            {
             groups.Add(name);
       }
   }
}
}
return groups.ToArray();
1

There are 1 answers

0
Sam Stephenson On BEST ANSWER

I did this by using a foreach loop But the following code still doesn't answer my question on how to do it for Principalsearcher

var groups = new List<string>();
PrincipalContext ctx = new PrincipalContext(ContextType.Domain);
GroupPrincipal qbeGroup = new GroupPrincipal(ctx);
PrincipalSearcher srch = new PrincipalSearcher(qbeGroup);
    foreach (var group in srch.FindAll())
    {
       if (group.Name.Contains("Administrators") || group.Name.Contains("Users"))
       {
             groups.Add(group.Name);
       }
    }
return groups.ToArray();