This blog has, IMO, some great resources. Unfortunately, some of those resources are becoming less relevant. I'm still blogging, learning tech and helping others...please find me at my new home on http://www.jameschambers.com/.

Thursday, June 4, 2009

Quick and Dirty Active Directory with c#

If you just want to grab some properties off a list of well-known entities in an Active Directory group, here’s some code to help you achieve that:

DirectoryEntry group = new DirectoryEntry(LDAP://CN=yourgroup,CN=users,DC=domain,DC=ca);
object members = group.Invoke("Members", null);
foreach (object member in (IEnumerable)members)
{
DirectoryEntry entry = new DirectoryEntry(member);

Console.WriteLine(entry.Name);
Console.WriteLine(" {0}", entry.Properties["telephoneNumber"].Value);
Console.WriteLine(" {0}", entry.Properties["displayname"].Value);
}


If you know the data is in there, but you’re not sure what it is called in Active Directory, you can change that foreach loop to the following to dump everything you’re allowed to see.  This is pretty trivial in any .Net language, and the Active Directory properties are easy to work with (they’re just a collection):



foreach (object member in (IEnumerable)members)
{
DirectoryEntry entry = new DirectoryEntry(member);
foreach (string prop in entry.Properties.PropertyNames)
{
Console.WriteLine(" {0}: {1}", entry.Properties[prop].PropertyName, entry.Properties[prop].Value);
}
break;
}



I added the break in there so it just dumps the properties of the first entity in the list. 



Obviously, you’ll want to change the “yourgroup”, “domain” and “com” to whatever your server is configured to use.  Then, you’ll be well on your way to extracting properties for users stored in Active Directory.

No comments:

Post a Comment