I wrote this to get the groups a particular user belongs to:
DirectoryEntry AD = new DirectoryEntry("WinNT://" + Environment.MachineName + ",computer");
DirectoryEntry user = AD.Children.Find(completeUserName, "user");
object obGroups = AD.Invoke("Groups");
foreach (object ob in (IEnumerable)obGroups)
{
// Create object for each group.
DirectoryEntry obGpEntry = new DirectoryEntry(ob);
listOfMyWindowsGroups.Add(obGpEntry.Name);
}
for (int j = 0; j < listOfMyWindowsGroups.Count; j++)
{
//ex
}
How is it possible to retrieve all the groups in windows and not just for a particular user?
How about setting up a filter for groups and enumerating the results.
Try this filter:
AD.Children.SchemaFilter.Add("group");
Try this one out, it will give you all groups in a specicied OU.
public ArrayList GetGroups()
{
ArrayList myItems = new ArrayList();
// Create the principal context for the group object.
PrincipalContext oPrincipalContext = new PrincipalContext(ContextType.Domain, sDomain, sDefaultOU, ContextOptions.SimpleBind, sServiceUser, sServicePassword);
// Create the GroupPrincipal object and set the diplay name property.
GroupPrincipal oGroupPrincipal = new GroupPrincipal(oPrincipalContext);
// Create a PrincipalSearcher object.
PrincipalSearcher oPrincipalSearcher = new PrincipalSearcher(oGroupPrincipal);
// Searches for all groups named "Administrators".
PrincipalSearchResult<Principal> oPrincipalSearchResult = oPrincipalSearcher.FindAll();
foreach (Principal oResult in oPrincipalSearchResult)
{
myItems.Add(oResult.Name);
}
return myItems;
}
For a full reference you can check this one out
.Net 3.5 version - > http://anyrest.wordpress.com/2010/06/28/active-directory-c/
Older versions - > http://anyrest.wordpress.com/2010/02/01/active-directory-objects-and-c/
来源:https://stackoverflow.com/questions/4019183/how-to-get-all-windows-groups