Find Active Directory groups that have a group name

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

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

However, I need all the groups starting with the name Groupname, for example, "GroupPrefix". Then I want to go through all these groups using the following code and save the “members” in an array / list, which I can use later for searching.

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

I would really appreciate any help I can get with this.

+6
source share
1 answer

You can use PrincipalSearcher and "query by example" to perform a search:

 // 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 done so, absolutely read the MSDN article, "Security Principles in the .NET Framework 3.5," which shows how to make better use of the new features in System.DirectoryServices.AccountManagement . Or look at the MSDN documentation in the System.DirectoryServices.AccountManagement namespace .

Of course, depending on your needs, you can specify other properties in this group-by-group request-by-example principle:

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

You can specify any of the properties in GroupPrincipal and use them as a "request by example" for your PrincipalSearcher .

+6
source

Source: https://habr.com/ru/post/978305/


All Articles