1

I am trying to make a phone directory by pulling OU names and phone numbers from AD. When searching to see if the phone field is filled out in the current OU, and that OU has children OU that also contain a telephone field, those user accounts are being returned as well. For example:

USA

---Texas

---Florida

---New York

I'm trying to find all users that have the phone field filled out in the USA OU but it's returning users from Texas, Florida, and New York. Is there a way to limit the depth of an LDAP search?

I am using c# and my current filter to find users is just

(&(objectClass=user)(objectCategory=person))

Any help would be greatly appreciated!

spork001
  • 15
  • 3
  • 1
    so you just want the users in the "root" OU "USA"? – curtisk Jan 26 '11 at 19:54
  • 1
    You can filter by phone number present using (telephoneNumber=*), or change telephoneNumber to another attribute depending on the field you need. We have Cisco IP phones here so we use (ipPhone=*). – Peter Jan 27 '11 at 15:31

1 Answers1

4

I am assuming you use DirectorySearcher to do the LDAP query. You can limit your search on the USA OU level by setting DirectorySearcher.SearchScope to SearchScope.OneLevel.

Here is a sample that it may look like

IEnumerable<DirectoryEntry> FindUsers(DirectoryEntry root)
{
    using (DirectorySearcher searcher = new DirectorySearcher(root))
    {
        searcher.Filter = "(&(objectClass=user)(objectCategory=person))";
        searcher.SearchScope = SearchScope.OneLevel;
        searcher.PageSize = 1000;
        foreach (SearchResult result in searcher.FindAll())
        {
            yield return result.GetDirectoryEntry();
        }
    }
}
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Harvey Kwok
  • 11,713
  • 6
  • 37
  • 59
  • 1
    Thanks for the response, I didn't know about SearchScope and it is exactly what I needed! – spork001 Jan 28 '11 at 16:33
  • 1
    @sport001 In case you wonder why I include PageSize = 1000 in the sample, please read my another post http://stackoverflow.com/questions/4693284/directorysearch-pagesize-2-doesnt-work/4693573#4693573. In almost all the cases, you want to set PageSize = 1000 so that you can return as many results as you need – Harvey Kwok Jan 28 '11 at 17:00