Windows IT Pro is the authoritative and independent resource for windows nt, windows 2000, windows 2003, windows xp. Features a collection of resources and magazines for windows IT professionals.
  
  
  Advanced Search 


April 11, 2005

Updating AD Attributes—Revisited

A popular script's makeover lets it work with usernames instead of DNs
RSS
Subscribe to Windows IT Pro | See More Active Directory (AD) Articles Here | Reprints | Or get the Monthly Online Pass—only $5.95 a month!

Download the Code Here

"Easily Update AD Attributes," July 2003, InstantDoc ID 39117, provides a script that updates attributes in Active Directory (AD) by using a comma-separated value (CSV) file or Microsoft Excel spreadsheet. Since the article's publication, I've received numerous email messages from administrators around the world telling me that the updateattribs.vbs script has saved them countless hours in their efforts to keep their AD user information up-to-date during moves and mergers.

Updateattribs requires that you supply the distinguished name (DN) of the users whose attributes you want to change. You can easily find a user's DN by using the Microsoft ldifde.exe, csvde.exe, or dsquery.exe command-line tool. However, some of the administrators who wrote to me had questions about how to obtain the DNs for their users, so I decided to make the script easier to use by revamping it to take the username as input. I also changed the parameters from unnamed to named.

The Original Version
Let's step back for a few minutes and look at how the original script operates. It requires at least two parameters. The first parameter is the input file formatted as a CSV file or Excel spreadsheet. The second parameter is the name of an output text file in which the script writes a detailed account of every action that it performs.

Figure 1 shows a sample input file, which has a header row that lists the names of the attributes to update in order starting with the DN. For each line in the input file (skipping the header row, of course), the script uses the Lightweight Directory Access Protocol (LDAP) provider to bind to the object's DN, then updates each attribute with the values specified in the input file. To save time, the script updates a value only when the value in the input file is different from the value in the AD object. Finally, the script outputs the results to the output file and writes statistics regarding how many objects were updated, how many attributes were updated, and how many errors occurred.

The New Script
The old script works well and executes fairly quickly, but as I mentioned above, it requires that the script's user provide an accurate DN for each user account he or she wants to modify. Because DNs aren't the typical format we use to identify our users, I decided to change the script so that it would use usernames instead. We all know how to retrieve our users' usernames, so it makes sense to use the username instead of the DN as the identifying field. However, to make changes to objects in AD by using LDAP, the script needs to convert the username to its DN.

In AD, the username is stored in a user account's sAMAccountName attribute. Thus, for each username in the input file, the script can query AD for a user object in which the sAMAccountName equals the username. The sAMAccountName attribute must be unique for each user so that the script's query will return one result, from which the script can extract the distinguishedName attribute, or no result, in which case the user doesn't exist in the domain. After obtaining the DN, the script can use it as the basis for the LDAP provider calls to update the desired user attributes.

Another change I made to the script was to use named instead of unnamed arguments. Named arguments let you specify the script's parameters in any order. For example, in a typical script, parameters are specified in a sequential order, as in

myscript.vbs parameter1
 parameter2

whereas named arguments can be specified as follows

myscript.vbs /p1:parameter1
 /p2:parameter2

or

myscript.vbs /p2:parameter2
 /p1:parameter1

The second and third examples are equivalent because each argument is labeled and can be retrieved from inside the script in any order. To find out whether a named argument was specified by the user, you use the WScript.Arguments.Named.Exists method, passing in the name of the parameter you want to check for. To retrieve the value of the named parameter, you use the WScript.Arguments.Named.Item function, which takes the name of the argument you want to retrieve and returns its value. Listing 1 shows an example of how named parameters are checked, retrieved, and stored in variables. Although using named arguments isn't a technical necessity for this script, it makes the script's syntax more familiar to users who are accustomed to specifying switches for command-line utilities.

Script Details
The syntax to run the new script is

updateattribs.vbs /i:inputfile
 /o:outputfile
 /basedn:DC=COMPANY,DC=COM
 /v:yes

where /i specifies the input file, /o specifies the output file, /basedn specifies the DN of the container (or node in the AD tree) in which to search for user accounts, and /v specifies whether to provide verbose output to the console. The first thing the script does is collect the values for the three required arguments: the input and output file names and the base DN. The fourth parameter, /v, is optional. The input file name specifies a CSV file or Excel spreadsheet such as that shown in Figure 2. The file or spreadsheet must have a header row that lists the attribute names to be updated, and the first column is reserved for the username. Each subsequent row contains the values for a user whose attributes require updating.

As you can see, the new input file is much simpler than the old one. Instead of having to specify a complete DN for each user object, you simply specify the username you want to update. The new input file and script provide the added advantage of being able to accommodate changes in your AD organization without you having to change the input file. If jsmith moves from one organizational unit (OU) to another, the input file is still valid because, unlike the DN, the username (i.e., sAMAccountName) doesn't change when an object moves.

To enhance performance, the script binds to LDAP://RootDSE and keeps a reference to it within the script, as Listing 2 shows. This technique effectively keeps a channel open between the LDAP provider and the server so that subsequent calls to the GetObject method execute much more quickly.

The script then uses the OpenTextFile function of Scripting.FileSystemObject to initialize the output file by creating it. And the script opens the input file by creating an instance of the Excel.Application COM object. It reads in the attribute names that are listed in the header row and stores them in the attributeNames array. This array will be used later to specify which attributes will be updated for the users. To see the code that performs these steps and download the complete code for the new Update-attribs script, go to http://www.windowsitpro.com/windowsscripting, enter InstantDoc ID 45814 in the InstantDoc ID text box, and click the 45814.zip hotlink.

At this point, the script's main loop starts to process each record in the input file. Starting with the second row in the file (the first detail row), the script reads in the first column—the user's username. The code then uses ActiveX Data Objects (ADO) to set up the ADs Provider to query AD starting from the base DN specified in the command-line arguments and look for a user object with a sAMAccountName that matches the username, as Listing 3 shows. If the result set contains a value, the script has found the user; if not, the script outputs an error and continues to the next record. When there's a match, the script reads the distinguishedName attribute into the dn variable and binds to it by using the GetObject method. This method returns a reference to the object, which the script stores in the ADObject variable.

The script can now update the attributes for the user objects referenced by ADObject. The script accomplishes this task by looping through the attributeNames array and checking the value of each attribute in AD and in the input file. If the values are different, the script uses the object's Put method to update the AD value. The Put method actually makes the change in the local cache rather than to AD. To make the changes permanent, the script commits them using the object's Setinfo method.

During its execution, the script uses a number of variables to keep a count of the number of objects and attributes that it's processed and updated as well as any errors it's received. All this information is used to create a summary that the script sends to both the screen and the output file. You'll also notice that when an attribute is updated, the script records the old and new values to the output file, so you can always use the output file to verify that changes have been made or to revert to the old values if necessary.

Running the Script
I've tested the new Updateattribs script on Windows XP Service Pack 1 (SP1) and SP2 and Windows 2000 Professional SP3 and SP4 machines, against both Windows Server 2003 and Win2K Server ADs. The script requires Excel 2000 or later to be installed (for parsing the input file) and has been tested for use with Excel 2003, Excel 2002, and Excel 2000. Due to the large amount of output the script generates when you enable verbose output, I highly recommend that you use cscript.exe to execute it.

Here are a few other tips for using the script:

  • Make sure you use the full path name to specify the input file (e.g., C:\scripts\myfile.csv). If the path includes any spaces, enclose the entire string in double quotes (e.g., "C:\My Documents\test.csv").
  • Make sure the attribute names you specify in your input file are exactly as they appear in AD (you can use adsiedit.msc or any similar tool to verify this). Attribute names are case sensitive.
  • If the script is unable to resolve usernames into DNs, make sure the base DN you specified is correct. For simplicity's sake, I typically use the domain name so that I can search the entire directory (e.g., DC=COMPANY,DC=COM; DC=CORP,DC=COMPANY,DC=COM).
  • If you have a large number of users and you know that all the users in your input file are contained within a particular OU structure, you can speed up the process by specifying a more granular base DN (e.g., OU=SALES,DC=COMPANY,DC=COM or even "OU=New York,OU=Sales,DC=COMPANY,DC=COM").

As with all new things, make sure you test Updateattribs in your test lab before using it in production. The script executes very quickly. Even in tests against an AD containing more than 100,000 objects, the script takes less than a second to update each record.

End of Article



Reader Comments
sdfsdaf

jhurleyaz April 13, 2006 (Article Rating: )


Although the script will update "normal" attributes, it does not seems to update abnormal attributes with [blank] fields with numeric characters only. The output says it was changed from [blank] to "xxxx", however the field remained blank. To do this, push alpha characters first, then the numeric characters. The reason this is important to us is we use purely numeric characters for our employee ids.

mmchughcelito March 15, 2007 (Article Rating: )


Thank you Steve Seguis, It works perfectly. This was just the script i was hoping to find, you saved my day (week and month!)

tom.j October 11, 2007 (Article Rating: )


You must log on before posting a comment.

If you don't have a username & password, please register now.




Top Viewed ArticlesView all articles
The Memory-Optimization Hoax

Don't believe the hype. At best, RAM optimizers have no effect. At worst, they seriously degrade performance. ...

Friday at PASS Europe 2006

Kevin talks about the closing day of the event and shares a funny Microsoft film. ...

Escape From Yesterworld

Kevin points you to the funniest SQL Server website ever! ...


Active Directory (AD) Whitepapers An Introduction to Windows Server 2008 Server Manager

Get More from Active Directory—Easily Audit Changes, and Secure and Restore Objects

User Provisioning: Get the Most Bang for your IT Buck

Related Events Check out our list of Free Email Newsletters!

Active Directory (AD) eBooks Keeping Your Business Safe from Attack: Monitoring and Managing Your Network Security

Keeping Your Business Safe from Attack: Encryption and Certificate Services

Windows 2003: Active Directory Administration Essentials

Related Active Directory (AD) Resources Become a VIP member of the Windows IT Pro community!
Get it all with the VIP CD and VIP access. A $500+ value for only $279!

Subscribe to Windows IT Pro!
Solve your toughest technical problems with our experts and access 10,000 + articles online. 30% off

Monthly Online Pass - Only $5.95!
Get instant access to 10,000+ articles from Windows IT Pro Magazine!

TechNet Virtual Labs
Evaluate and test Microsoft's newest products.

Job Openings in IT


ADS BY GOOGLE SPONSORED LINKS FEATURED LINKS

Maximize your SharePoint Investment – 8 Cities
Discover best practices and tips for both architecting and administering SharePoint. Early Bird Price of $99 through Sept 15th.

Find a new job now on the all new IT Job Hound!
Search jobs, post your resume, and set up job e-mail alerts!

Master SharePoint with 3 eLearning Seminars
Learn how to build a better SharePoint infrastructure and enable powerful collaboration with MVPs Dan Holme and Michael Noel. Register today!

Top Tools for Virtualization Disaster Recovery & Replication
View this web seminar on August 14th to learn about two tools that will result in faster backup and restore with P2V disaster recovery.

SharePointConnections Conference Fall 2008
Don’t miss the premier event for Microsoft IT Professionals in Las Vegas, November 10-13. Register and book your room by August 25 and receive a FREE room night (based on a three night minimum stay).

VMworld 2008 - Sign Up Today!
Join your peers on September 15-18 at The Venetian Hotel in Las Vegas as VMware hosts VMworld 2008, the leading Virtualization event.



Entrust Unified Communications Certs
Secure Exchange 2007 and save 20%. Now through Sept. 2008.

Increase Application Performance
Free White Paper by Editor's Best winner, Texas Memory Systems.

Need to convert between XML, DBs, EDI, and Excel? Try MapForce free!
Drag & drop to transform between popular data formats – get results instantly or generate code.

Microsoft® Tech•Ed EMEA 2008 IT Professionals
Advance your thinking with new ideas and practical real-world solutions at Microsoft’s FIVE day technical infrastructure conference 3-7 Nov., 2008. Register before 26 September 2008 to save €300.

Order Your SQL Fundamentals CD Today!
Learn how to use SQL Server, understand Office integration techniques and dive into the essentials of SQL Express and Visual Basic with this free SQL Fundamentals CD.

Are You Really Compliant with Software Regulations?
View this web seminar that will help you with compliance best practices and check out a management solution to assure that you won’t be in jeopardy of an audit.

Virtualization Congress Oct. 14-16 in London
Don't miss Virtualization Congress, the premiere EMEA conference dedicated to hardware, OS and application virtualization. Oct. 14-16.
Windows IT Pro Home Register FAQ for Windows WinInfo News
Europe Edition About Us Contact Us/Customer Service Media Kit Affiliates / Licensing  
SQL Server Magazine Office & SharePoint Pro Windows Dev Pro IT Job Hound ITTV
IT Library Technical Resources Directory Connected Home Windows Excavator Windows SuperSite 
 
 Windows IT Pro is a Division of Penton Media Inc.
 Copyright © 2008 Penton Media, Inc., All rights reserved. Terms and Use | Privacy Statement | Reprints and Licensing