Scripting the Active Directory


Well, sometimes the built-in MMC snap-in doesn’t do it all. In this case you need to do more than just add another user. Of course there a bunch of different ways to access your Active Directory. You most certainly can write a nifty c# programm, which could do all kinds of operations. But a lot of times you will end up write some little VBScript, just because it’s so darmn simple.

The Story

For the purpose of illustrating the usage of Active Directory scripting I have a little sample setup. Assume you have a database containing employee data and you want to sync this data with your Active Directory instance. You could further use this data in Active Directory to enable Active Directory aware programs (like SharePoint 🙂 ) to access this data.

The Basics

OK; to get started I will show a little script, which access the Active Directory and does some mass-updating off user-accounts. For example say you want to add employee-numbers to the users accounts.

First of all, you need to connect to the directory. For this you need to know the root path of your Active Directory, or as a convenience you might as well use LDAP://RootDSE instead. OK, let’s get connected to our Active Directory; the code below assumes you have a recordset called rstEmployees which holds our employee data. So we iterate over the recordset:

Sub UpdateActiveDirectoryEntries
        On Error Resume Next
        Dim objRoot, objUser
          Dim intEmployeeCount
        Set objRoot = GetObject(strRootADPath)
        WScript.Echo "Processing records ..."
        While Not rstEmployees.EOF
                WScript.Echo "processing:" & rstEmployees.Fields("EmployeeName") & " (" & rstEmployees.Fields("EmployeeNumber") & ")"
                  Set objUser = GetObject("LDAP://CN=" & rstEmployees.Fields("EmployeeName") & "," & strAllEmployeeADPath)
                  If objUser Is Nothing Then
        WScript.Echo "User '" & rstEmployees.Fields("EmployeeName") & "' could not be found!"
                        ShowUser objUser
                          WScript.Echo "Writing ..."
                          objUser.Put "EmployeeID", rstEmployees.Fields("EmployeeNumber").Value
                          objUser.Put "EmployeeNumber", rstEmployees.Fields("EmployeeNumber").Value
                          ' objUser.PutEx ADS_PROPERTY_CLEAR, "EmployeeNumber",  vbNullString
                          ShowUser objUser
                  End If
                  Set objUser = Nothing
  End Sub

Leave a Comment.