Querying Active Directory

#import sys
#sys.path.append(r'C:\WINDOWS\system32\windowspowershell\v1.0')

import System,clr
clr.AddReference("System.DirectoryServices")
from System.DirectoryServices import DirectoryEntry

#Script settings. Change this accordinglymyPath = "LDAP://DC=americas,DC=ent,DC=contoso,DC=com"
myFilter = "(SAMAccountName=jlevi)"

root = DirectoryEntry(myPath)
search = System.DirectoryServices.DirectorySearcher(root) 
search.Filter = myFilter
resultCol = search.FindOne();

#get individual AD attributes 
print "Path:\t",resultCol.Properties["distinguishedname"][0]
print "Dir:\t",resultCol.Properties["homedirectory"][0]
print "Email:\t",resultCol.Properties["userprincipalname"][0]

#dump all attributes for the given result node

print str("_ ")*50
for key in resultCol.Properties.PropertyNames:
   for val in resultCol.Properties[key]: 
      #last print arg truncates val to 200 chars 
      print key,":\t\t\t",str(val)[0:200]

Reference: System.DirectoryServices, DirectoryEntry Class
Previous
Next Post »