Connecting to Active Directory

From IronPython Cookbook

This example is adapted from a post by the Powershell Guy]. It connects to the Active Directory RootDSE and lists its children.

You need Powershell 1.0 installed, but this example doesn't run under Powershell, instead you use a Powershell assembly from IronPython.

(Note that the example assumes the default install directory of Powershell - C:\WINDOWS\system32\windowspowershell\v1.0.)

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

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

root = System.DirectoryServices.DirectoryEntry()
for c in root.Children:
    print c.Name

This should print something like... (Depending on your ActiveDirectory state of course)

CN=Builtin
CN=Computers
OU=Domain Controllers
CN=foo
CN=ForeignSecurityPrincipals
CN=Infrastructure
CN=Ken Myer
CN=LostAndFound
OU=MowOtherOU
OU=MowOu
CN=NewUs:::er0003
CN=NewUser0010
CN=NewUser0011
CN=NewUser0012
CN=NTDS Quotas
CN=Program Data
CN=System
CN=Users

Or another example:

from System.DirectoryServices import DirectoryEntry

root = DirectoryEntry()
u = root.Children.Add("CN=fooBar", "User")
print u.Name
'CN=fooBar'


Back to Contents.

TOOLBOX
LANGUAGES