使用DirectoryServices.AccountManagement从OU获取组

我想使用AccountManagement列出组织单位中的所有组。

以下代码段与DirectoryServices一起使用,但我必须在结果中使用DirectoryEntry路径实现GroupPrincipal(这感觉就像一个脏修复)。

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(); 

有人有想法吗?

谢谢!

您可以将PrincipalContext设置为要开始搜索的OU,并使用System.DirectoryService.AccountManagementPrincipalSearcher -class来完成所需的操作,如下所示:

 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();