Getting User Information For all the users in an Active Directory Group.
A recent requirement came up for a quick bit of code to retrieve the names and e-mail addresses from an ActiveDirectroy group. I did this in code instead of power shell in order to be able to use these methods in further logic.
So here we go….
First we’re going to create a simple structure to represent the user information we need:
public struct UserInfo
{
public string DisplayName;
public string Mail;
public string Login;
}
Next were going to create a simple entry point in which we will use to test our methods:
static void Main(string[] args) { ArrayList ar = GetADGroupUsers("GroupName"); List<UserInfo> users = new List<UserInfo>(); foreach (string user in ar) { users.Add(GetADUserInfo(user)); } }
Now we will need to implement the two methods seen above. First the method to get all the users in a group:
static public ArrayList GetADGroupUsers(string groupName) { SearchResult result; DirectorySearcher search = new DirectorySearcher(); search.Filter = String.Format("(cn={0})", groupName); search.PropertiesToLoad.Add("member"); search.PropertiesToLoad.Add("mail"); search.PropertiesToLoad.Add("samaccountname"); result = search.FindOne(); ArrayList userNames = new ArrayList(); if (result != null) { for (int counter = 0; counter < result.Properties["member"].Count; counter++) { userNames.Add((string)result.Properties["member"][counter]); } } return userNames; }
Now that we have the ArrayList of users, we will need to get the information about the users:
static public UserInfo GetADUserInfo(string userName) { SearchResult result; DirectoryEntry de = new DirectoryEntry("LDAP://mydomaincontroller/"+userName); UserInfo ui = new UserInfo(); ui.DisplayName = de.Properties["displayName"].Value.ToString(); ui.Mail = de.Properties["mail"].Value.ToString(); ui.Login = de.Properties["sAMAccountName"].Value.ToString(); return ui; }
And that’s it, now we have a nice list of users with their email addresses.