Wednesday, October 14, 2009

Getting users for an AD Group

Scenario:
For one of our requirements , We needed to pull all the users for a specific AD Group.

Solution:
You know me , right.. always ready to code something... :-)

Note:
I am using HostingEnvironment.Impersonate() to be able to make the code run ASP.Net Application Pool context. If you are using it from console application, you may not need this.

Code:

using System;
using System.Collections.Generic;
using System.Text;
using System.DirectoryServices;
using System.Reflection;
using System.Web.Hosting;

public static List<string> GetGroupMembers(string domainName, string ADConnectionString, string strGroup)
{
List<string> groupMembers = new List<string>();

try{
using (HostingEnvironment.Impersonate())
{
if (string.IsNullOrEmpty(ADConnectionString))
throw new Exception("ADConnectionString value is Empty");

//connects to the given AD based on given AD string
DirectoryEntry ent = new DirectoryEntry("LDAP://" + ADConnectionString);

//ones connected to the AD it searches for given/named group
DirectorySearcher srch = new DirectorySearcher("(CN=" + strGroup + ")");

SearchResult rs = srch.FindOne();

ResultPropertyCollection resultPropColl = rs.Properties;

foreach (Object memberColl in resultPropColl["member"])
{
//get the info about specific AD user from AD
DirectoryEntry gpMemberEntry = new DirectoryEntry("LDAP://" + memberColl);

// PrintDirectoryEntryProperties(gpMemberEntry);
System.DirectoryServices.PropertyCollection userProps = gpMemberEntry.Properties;

object objVal = userProps["sAMAccountName"].Value;

if (null != objVal)
{
if (gpMemberEntry.SchemaClassName == "user")
{
groupMembers.Add(domainName + "\\" + objVal.ToString());
}
//else
//{
//// Un-comment and test this section for recursively finding users
// groupMembers.AddRange(GetGroupMembers(domainName, ADConnectionString, objVal.ToString()));
//}
}
}
}
}
catch (Exception ex)
{
// Log.Error(ex.ToString());
}
return groupMembers;
}
Articles:
Impersonation

0 comments: