Tim Van Wassenhove

Passionate geek, interested in Technology. Proud father of two

04 Nov 2006

Querying Active Directory

A while ago i wanted to figure out which demo accounts i had already created in my Active Directory. Since i was smart enough to give them all a description ‘Demo User’ this was easily done as following

using( DirectoryEntry directoryEntry = new DirectoryEntry() )
{
	using( DirectorySearcher directorySearcher = new DirectorySearcher() )
	{
		directorySearcher.Filter = "(&(objectClass=user)(description=Demo User))";
		directorySearcher.SearchScope = SearchScope.Subtree;
		directorySearcher.Sort = new SortOption("displayname", SortDirection.Ascending );

		SearchResultCollection results = directorySearcher.FindAll();
		foreach( SearchResult result in results )
		{
			ResultPropertyCollection propertyCollection = result.Properties;
			Console.WriteLine( "{0}: {1}", propertyCollection\["displayname"\]\[0\].ToString(), propertyCollection\["description"\]\[0\].ToString() );
		}
	}
}