dotNoted

Icon

Observations of .Net development in the wild

Getting more than 1000 results from a DirectorySearcher query

Ok, this isn’t exactly clear. Need to make a note of this so I don’t forget it. The DirectorySeacher only returns 1000 results when the defaults are used. This setting actually comes from an AD server, not the .Net stuff, or even the ADSI or LDAP protocol implementation which are under the covers. So, basically, it’s as good as hard-coded. ADSI helps out here, and we can take advantage of it, by just setting the DirectorySearcher.PageSize to a number besides 0. I like to set it to the DirectorySearcher.SizeLimit default which is 1000 (actually, it’s 0, but this means 1000). This actually makes ADSI make as many paged requests as needed to get the entire result set, not just the first SizeLimit records. The docs aren’t terribly clear on this, and I try to make repeated requests to the server until the resulting SearchResultsCollection’s Count property is less than the searcher’s PageSize property… which doesn’t work since ADSI has done this bit for me and now I’m sitting with all the results in the collection. Here’s how to get all the users (with a few properties) in the domain [in IronPython]:

import clr
from System import *
clr.AddReference("System.DirectoryServices")
from System.DirectoryServices import *
from System.Collections.Generic import *

searcher = DirectorySearcher()
searcher.PageSize = 1000

def GetDomainUsers():

  searcher.Filter = "(&(objectClass=user)(sAMAccountName=*)(!objectClass=computer))"
  searcher.PropertiesToLoad.Add("userPrincipalName")
  searcher.PropertiesToLoad.Add("userAccountControl")
  searcher.PropertiesToLoad.Add("sAMAccountName")
  l = List[SearchResult]()
  domainResults = searcher.FindAll()

  l.AddRange(domainResults)
  domainResults.Dispose() # Get rid of the unmanaged ADSI resources ASAP

return l

Filed under: .Net Basics

Leave a comment