Looking for LDAP query to get only those OUs from Active Directory having group in it.
most important is only using LDAP query, I don't want to filter each OU using C# code.
Thanks
Groups can be stored in organizationalUnits but also in domain, containers.
Using DirectoryEntry or AccountManagement you can do the following :
Here is a solution using System.DirectoryServices.AccountManagement
and System.DirectoryServices
/* Retreiving a principal context
*/
PrincipalContext domainContext = new PrincipalContext(ContextType.Domain, "WM2008R2ENT:389", "dc=dom,dc=fr", "jpb", "PWD");
/* Look for all the groups from the root
*/
GroupPrincipal allGroups = new GroupPrincipal(domainContext);
allGroups.Name = "*";
/* Bind a searcher
*/
PrincipalSearcher searcher = new PrincipalSearcher();
searcher.QueryFilter = allGroups;
PrincipalSearchResult<Principal> hRes = searcher.FindAll();
/* Read The result
*/
List<DirectoryEntry> listContainerWithGroups = new List<DirectoryEntry>();
foreach (GroupPrincipal grp in hRes)
{
DirectoryEntry deGrp = grp.GetUnderlyingObject() as DirectoryEntry;
if (deGrp != null)
listContainerWithGroups.Add(deGrp.Parent);
}
/* Get Unique Entries
*/
var listContainerWithGroupsUnique = from o in listContainerWithGroups
group o by o.Properties["distinguishedName"].Value into dePackets
select dePackets.First();
foreach (DirectoryEntry deTmp in listContainerWithGroupsUnique)
{
Console.WriteLine(deTmp.Properties["distinguishedName"].Value);
}
This isn't possible with a single search. You'll need to grab each OU and then do a one-level search of that OU for (&(objectCategory=group)(objectClass=group)). This is not going to be particuarly efficient when you consider how many searches you might need to perform. Also consider whether or not you need to handle the scenario where you have OU=A\\OU=B. If OU=B includes the group, do you include OU=A (the parent)?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.