How do I get a list of all the users in a specific department using DirectorySearcher and Filter/PropertiesToLoad?
I know how to filter using a username and get the department name for a user, but I do not know how to specify a department and get a list of staff who are part of the department.
Any assistance appreciated!
e.g.
var search = new DirectorySearcher(new DirectoryEntry("LDAP://DC=au,DC=company,DC=com"));
search.Filter = "(sAMAccountName=" + userID + ")"; // put the identity name here
search.PropertiesToLoad.Add("cn");
search.PropertiesToLoad.Add("department");
var res = search.FindOne();
If you want to use the old-style
DirectorySearcher, then the trick is to bind to the OU that you want to list the users for, e.g. your deparment:and then do a
and iterate over the results.
The other option would be to use the newer
System.DirectoryServices.AccountManagementnamespace and use it's strongly-typed, easy-to-use classes such as thePrincipalSearcherand a "query-by-example" principal to do your searching:If you haven't already - absolutely read the MSDN article Managing Directory Security Principals in the .NET Framework 3.5 which shows nicely how to make the best use of the new features in
System.DirectoryServices.AccountManagement. Or see the MSDN documentation on the System.DirectoryServices.AccountManagement namespace.Of course, depending on your need, you might want to specify other properties on that "query-by-example" user principal you create:
DisplayName(typically: first name + space + last name)SAM Account Name- your Windows/AD account nameUser Principal Name- your "[email protected]" style nameYou can specify any of the properties on the
UserPrincipaland use those as "query-by-example" for yourPrincipalSearcher.Update: to get the members of a group, use this code: