Reputation: 4319
I am using the following query in AD to bring back a user's mail address:
// get a DirectorySearcher object
DirectorySearcher search = new DirectorySearcher();
// specify the search filter
search.Filter = "(&(objectClass=user)(anr=" + login + "))";
// specify which property values to return in the search
search.PropertiesToLoad.Add("mail"); // smtp mail address
// perform the search
SearchResult result = search.FindOne();
if (result != null)
{
return result.Properties["mail"][0].ToString();
}
else
{
return null;
}
For a particular user who's login is "SRB" the query is bringing back a computer object called "SRB-PC".
I don't understand why as the filter says objectClass should be "user".
Also - why is it bringing it back as it were a "like" query - I want it to bring back only objects whose name exactly match the filter.
Upvotes: 1
Views: 2627
Reputation: 10996
You will do well to use something like:
(&(objectCategory=person)(objectClass=user))
or
(sAMAccountType=805306368)
See some other MS queries.
Upvotes: 1
Reputation: 94654
A Computer
object is a sub Class of a User
object in Active Directory. This is the reason why you find computers for your original search.
The objectCategory
element is used to distinguish entities properly:-
as stated in the Object Class vs. Object Category page:
Prior to Windows Server 2008, the objectClass attribute is not indexed. This is because it has multiple values and is highly non-unique; that is, every instance of the objectClass attribute includes the top class. This means an index would be very large and ineffective. To locate objects of a given class, use the objectCategory attribute, which is single-valued and indexed. For more information about using these properties in search filters, see Deciding What to Find.
So it is far more efficient to search using the objectCategory instead of the objectClass.
Upvotes: 2
Reputation: 4319
OK - switched the filter to:
search.Filter = string.Format("(&(objectCategory=Person)(anr={0}))", login);
Don't really understand why it fixed it, but it did!
Upvotes: 1