Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Groups From OU using DirectoryServices.AccountManagement

I'd like to use AccountManagement to list all the groups in an Organizational Unit.

The following snippet works with DirectoryServices but I would have to instanciate GroupPrincipal with the DirectoryEntry path in the result (which feels like a dirty fix).

DirectoryEntry root = new DirectoryEntry("LDAP://OU=Marketing,OU=Operations,OU=Applications,DC=mycompany,DC=local")
        DirectorySearcher ds = new DirectorySearcher(root);
        ds.Filter = "(objectCategory=group)";
        SearchResultCollection results = ds.FindAll();

Has anyone an idea?

Thanks!

like image 727
teebot Avatar asked Dec 18 '09 09:12

teebot


People also ask

How to get the list of AD user group memberships?

In .NET C#, we can get the list of AD user group memberships using two methods. In first method, we can get nested groups from the constructed attribute TokenGroups, it requires the dll reference System.DirectoryServices (It is available from .NET Framework 2.0).

How do I add or remove a user from a group?

To add a user to a group, you should add the UserPrincipal object that holds the reference of a user to this enumeration. And the same logic for removing a user from a group: you must remove that user from the enumeration. But, do not forget to execute the Save method of GroupPrincipal after making changes.

What is the overloaded method getauthorizationgroups return?

This overloaded method only returns the groups of which the principal is directly a member; no recursive searches are performed. Recursive search results are available for user principal objects. For more information, see the GetAuthorizationGroups method.

How to get the members of a group using groupprincipal?

UserPrincipal insUserPrincipal = (UserPrincipal)lbUsers.SelectedItem; insUserPrincipal.SetPassword ( "12345678" ); MessageBox.Show ( "Password changed." ); You can get the members of a group from the Members property of the GroupPrincipal object. You can use this property as an enumeration.


1 Answers

You can set the PrincipalContext to the OU where you want to start the search and use the PrincipalSearcher-class in System.DirectoryService.AccountManagement to accomplish what you need, like this:

PrincipalContext yourOU = new PrincipalContext(ContextType.Domain, "mycompany.local", "OU=Marketing,OU=Operations,OU=Applications,DC=mycompany,DC=local");
GroupPrincipal findAllGroups = new GroupPrincipal(yourOU, "*");
PrincipalSearcher ps = new PrincipalSearcher(findAllGroups);
foreach(var group in ps.FindAll())
{
  Console.WriteLine(group.DistinguishedName);
}
Console.ReadLine();
like image 159
Per Noalt Avatar answered Oct 04 '22 05:10

Per Noalt