11

I need to write a C# script that returns all the Active Directory groups with group names that start with a certain name. I know can return one group using the following code.

PrincipalContext ctx = new PrincipalContext(ContextType.Domain);
GroupPrincipal grp = GroupPrincipal.FindByIdentity(ctx, IdentityType.Name, "Groupname");

However, I want all the groups where the Groupname starts with, say "GroupPrefix". I then want to traverse all these groups using the following code and store the "members" in an array/list that I can use later for searching.

foreach (UserPrincipal p in grp.GetMembers(true))

I would much appreciate any help that I can get with this.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Raj
  • 549
  • 2
  • 11
  • 25

1 Answers1

14

You can use a PrincipalSearcher and a "query-by-example" principal to do your searching:

// create your domain context
using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain))
{
   // define a "query-by-example" principal - here, we search for a GroupPrincipal 
   // and with the name like some pattern
   GroupPrincipal qbeGroup = new GroupPrincipal(ctx);
   qbeGroup.Name = "GroupPrefix*";

   // create your principal searcher passing in the QBE principal    
   PrincipalSearcher srch = new PrincipalSearcher(qbeGroup);

   // find all matches
   foreach(var found in srch.FindAll())
   {
       // do whatever here - "found" is of type "Principal"
   }
}

If you haven't already - absolutely read the MSDN article Managing Directory Security Principals in the .NET Framework 3.5 which shows nicely how to make the best use of the new features in System.DirectoryServices.AccountManagement. Or see the MSDN documentation on the System.DirectoryServices.AccountManagement namespace.

Of course, depending on your need, you might want to specify other properties on that "query-by-example" group principal you create:

  • DisplayName (typically: first name + space + last name)
  • SAM Account Name - your Windows/AD account name

You can specify any of the properties on the GroupPrincipal and use those as "query-by-example" for your PrincipalSearcher.

Luis
  • 5,979
  • 2
  • 31
  • 51
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459