Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get user names in an Active Directory Group via .net

The below code gets me the users in the group but it is returned "CN=johnson\,Tom,OU=Users,OU=Main,DC=company,DC=com"

I want to just return the First and Last name. How can I accomplish this?

DirectoryEntry ou = new DirectoryEntry();
DirectorySearcher src = new DirectorySearcher();

src.Filter = ("(&(objectClass=group)(CN=Gname))");
SearchResult res = src.FindOne();
if (res != null)
{
    DirectoryEntry deGroup = new DirectoryEntry(res.Path);
    PropertyCollection pcoll = deGroup.Properties;

    foreach (object obj in deGroup.Properties["member"])
    {
            ListBox1.Items.Add(obj.ToString());
    }
}
like image 813
Eric Avatar asked Feb 04 '11 18:02

Eric


People also ask

How do I get a list of users in ad group?

PowerShell Get-AdGroupMember is used to get members from the active directory. You can get ad group members by specifying the active directory group name. The Identity parameter specifies the Active Directory Group to access to get members of the group.


2 Answers

I prefer using the classes in System.DirectoryServices.AccountManagement:

PrincipalContext principalContext = new PrincipalContext(ContextType.Domain);
GroupPrincipal group = GroupPrincipal.FindByIdentity(principalContext, "GName");

Search through the group.Members property until you have a Principal that you want. Then extract the name like this:

foreach (Principal principal in group.Members)
{
   string name = principal.Name;
}
like image 50
Russell McClure Avatar answered Sep 24 '22 14:09

Russell McClure


Using your code, the givenName (first name) and sn (last name) properties should work.

If you use the System.DIrectoryServices.AccountManagement namespace UserPrincipal (as @russell-mcclure suggested), you will find GivenName and Surname properties also.

AccountManagement is very handy unless you have to traverse a trusted forest and need the global catalog to find the user.

like image 37
bigtlb Avatar answered Sep 25 '22 14:09

bigtlb