Tim Van Wassenhove

Passionate geek, interested in Technology. Proud father of two

05 Mar 2008

Find the members of an AD group

Because i always seem to forget about the syntax of LDAP Search Filters (RFC 2254: The String Representation of LDAP Search Filters and Creating a Query Filter) i’m going to post a basic demo of DirectorySearcher that returns the members that are part of a given AD group

private static void Main(string[] args)
	foreach (string member in FindUsernames("CWBE-PS-.NetDev"))

	Console.Write("{0}Press any key to continue...", Environment.NewLine);

private static IEnumerable<string> FindUsernames(string groupname)
	string filter = "(&(&(objectCategory=Group)(objectClass=Group))(name={0}))";
	filter = string.Format(filter, groupname);

	DirectoryEntry directoryEntry = new DirectoryEntry();
	DirectorySearcher searcher = new DirectorySearcher(directoryEntry);
	searcher.SearchScope = SearchScope.Subtree;
	searcher.Filter = filter;

	DirectoryEntry groupEntry = searcher.FindOne().GetDirectoryEntry();
	PropertyValueCollection members = (PropertyValueCollection)groupEntry.Properties["member"];
	return ConvertAll<object, string>((object[])members.Value);

private static IEnumerable<to> ConvertAll<from, To>(IEnumerable<from> elements)
	Type toType = typeof(To);

	foreach (From element in elements)
		yield return (To)Convert.ChangeType(element, toType);