How to get all windows groups?

梦想与她 提交于 2019-12-10 11:27:53

问题


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?


回答1:


How about setting up a filter for groups and enumerating the results.

Try this filter:

AD.Children.SchemaFilter.Add("group");



回答2:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!