Querying Active Directory with DirectorySearcher

From IronPython Cookbook

Adapted from an entry on the DotNoted Blog].

Fetching all the users (with a few properties) in the domain:

import clr
clr.AddReference("System.DirectoryServices")
from System.DirectoryServices import DirectorySearcher

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")
    domainResults = searcher.FindAll()
    results = list(domainResults)

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

    return results


Back to Contents.

TOOLBOX
LANGUAGES