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());
}
}
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.
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;
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With