Update active directory user attributes from a CSV File. (See Notes section for additional information and instructions) Notes
Introduction
This script can be used to update Active Directory User attributes from a CSV file. One column in the CSV file is used to match rows in the CSV file to user accounts in Active Directory and the other columns are used to update attributes. Normally the Pre-Windows 2000 username (sAMAccountName) attribute is used to match rows in the CSV file to user accounts in Active Directory, but you can easily modify the script to use a different attribute if required. For example, you might want to identify the user account you want to update in the CSV file by email address (mail attribute) rather than username. As an alternative to this script, you might also to consider using the free Bulk AD Users application available on this website. Bulk AD Users supports updating users via CSV file and it includes some other tools for updating users accounts such as the Edit In Excel and Bulk Modify features. The Bulk AD Users application can make it easier for you to apply the update and it also produces an XML log file of the update which can be used to rollback changes. That’s not to say that Bulk AD Users is a complete replacement for this script as the script allows you to customise the code for your own requirements, and it can also be automated via task manager if required.
Bulk Update Considerations
There is always an element of risk involved in performing bulk updates to Active Directory. Please be sure to test updates in a QA environment before applying them to your live domain. Also, it’s a good idea to have a plan of action prepared should something go wrong with the update. Taking a backup of your Active Directory database is a sensible precaution, and it also pays to be familiar with backup and restore techniques. If you have a large domain or a domain that is connected over slow WAN links, you might also need to consider the impact of replication traffic when performing bulk updates. Bulk updates can save an enormous amount of time and they normally run very smoothly if planned correctly.
Setup
The first step in updating user accounts from a CSV file is to produce a valid CSV input file for the script. A CSV file is simply a text file containing rows and columns of data like a spreadsheet and they can be read and written to by spreadsheet applications like Microsoft Excel. There is normally a way to extract data from databases into CSV text files. It’s also possible to produce a text file manually by using an application such as notepad. See here for more information on producing CSV files. As well as taking care to ensure that the CSV file you have produced is valid, you also need to ensure that the CSV file includes a header row. The header row is used by the script to identity the column names and the column names should correspond to the attribute names used by Active Directory. The attribute names are not always obvious, so please take care to ensure that you are using the correct names. For example, the surname attribute is “sn” and the first name attribute is “givenName”. As mentioned previously, the username (pre windows 2000) is used by default to match rows in the CSV file to the user accounts in Active Directory. This attribute name is “sAMAccountName” and must be included in your CSV file (unless you plan to use a different search attribute). If you don’t want to edit the script, the CSV file should be called “usermod.csv” and it should be located on the root of the “C:\” drive. If you want to use a different filename or location, edit the _strCSVFolde_r and strCSVFile attributes in the setup section of the script. Change the strSearchAttribute if you want to use a different attribute for matching rows in the CSV file to users in Active Directory (e.g. userPrincipalName or mail attribute). The attribute you choose for the strSearchAttribute should be unique as the script expects a maximum of 1 user to be returned for any attribute value. If multiple users are found with the same attribute value, no user accounts will be updated. The configuration of the script and the CSV file is now complete. The script is designed to run in cscript mode (described in this article). If you double click the script, the script will run in wscript mode - the script will work ok, but you will get a lot of annoying prompts. To run in cscript mode, open a command prompt and change the current directory to the one that contains the script. Use the following command to run the script: cscript csv_user_update.vbs The results of the script will be output to the console window. If you prefer to have the results stored in a text file, use the following command instead: cscript csv_user_update.vbs » results.txt
Extracting CSV Data From Active Directory
If you would like to extract data as a CSV file from Active Directory as a base for your update, please refer to the scripts below:
The script should support most single-valued attributes by default. In addition, special handling has been added for the following attributes:
Attribute Name
Description
cn
This attribute is the "Name" column that is shown in Active Directory Users & Computers and it's a standard attribute in AD. The cn (common name) forms part of an objects distinguished name. This attribute must be unique within it's parent container (organizational unit). This attribute can be read the same as any other attribute, but to change the value you need to use the "MoveHere" method.
TerminalServicesProfilePath
Terminal Services attributes are stored in the "userparameters" attribute in Active Directory. Modifying this attribute directly isn't recommended, but it is possible to modify these attributes via the IADsTSUserEx interface. The TsUserEx.dll is required to modify these values, otherwise you will get a "Object doesn't support this property or method" error. To fix this you will need to install the Windows 2000/2003 Administration Tools Pack.
TerminalServicesHomeDirectory
TerminalServicesHomeDrive
AllowLogon
Password
Microsoft doesn't provide any access to user passwords stored in Active Directory via ADSI, either in encrypted or unencrypted format. It is possible to change a password by calling the "SetPassword" method though. The script won't output the previous value as it does with other attributes. Note: Please take care to ensure passwords meet length and complexity requirements.
Manager_sAMAccountName
The manager attribute in active directory requires a distinguished name. e.g. CN=David.Wiseman,OU=MyUsers,DC=WiseSoft,DC=co,DC=UKTo make this attribute easier to modify, you can specify "Manager_sAMAccountName" as the attribute name in the CSV header instead of "manager". This allows you to use the username (Pre Windows 2000) instead of the manager's distinguished name. e.g.David.Wiseman
You might want to refer to the Active Directory Schema Guide to help identify the correct attribute names for other attributes. Note: Bulk AD Users provides better support for multi-valued attributes if required.
Troubleshooting
Provider cannot be found error
The script uses the Microsoft.Jet.OLEDB.4.0 provider. If you are using x64, you will need to use the 32bit script host for this provider to be available. To do this, open a command prompt and navigate to the “SysWow64” folder in your Windows directory. e.g. C:\Windows\SysWOW64\ You can now run cscript from this location, passing the full location of your script file. e.g. cscript “C:\update_users_csv.vbs”
Data Not Imported as Expected
This script uses the Microsoft.Jet.OLEDB.4.0 provider for parsing the CSV file. Sometimes the data type gets mis-interpreted and the data is not imported as expected. An example of this is where you are updating the telephoneNumber attribute and your telephone numbers start with a leading zero. The provider is likely to interpret this as a number rather than a string which results in the leading zeros getting truncated. To get around this issue, you can create a schema.ini file. If you have a CSV file consisting only of sAMAccountName and telephoneNumber columns, your schema.ini file might look something like this: [usermod.csv] ColNameHeader=True Format=CSVDelimited Col1=sAMAccountName Text Col2=telephoneNumber Text For more information on schema.ini files, please refer to this article.
OPTIONEXPLICIT' Variables must be declared
' *************************************************
' * Instructions
' *************************************************
' Edit the variables in the "Setup" section as required.
' Run this script from a command prompt in cscript mode.
' e.g. cscript usermod.vbs
' You can also choose to output the results to a text file:
' cscript usermod.csv >> results.txt
' *************************************************
' * Constants / Decleration
' *************************************************
CONSTadOpenStatic=3CONSTadLockOptimistic=3CONSTadCmdText=&H0001CONSTADS_PROPERTY_CLEAR=1DIMstrSearchAttributeDIMstrCSVHeader,strCSVFile,strCSVFolderDIMstrAttribute,userPathDIMuserChangesDIMcn,cmd,rsDIMobjUserDIMoldVal,newValDIMobjFieldDIMblnSearchAttributeExists' *************************************************
' * Setup
' *************************************************
' The Active Directory attribute that is to be used to match rows in the CSV file to
' Active Directory user accounts. It is recommended to use unique attributes.
' e.g. sAMAccountName (Pre Windows 2000 Login) or userPrincipalName
' Other attributes can be used but are not guaranteed to be unique. If multiple user
' accounts are found, an error is returned and no update is performed.
strSearchAttribute="sAMAccountName"'User Name (Pre Windows 2000)
' Folder where CSV file is located
strCSVFolder="C:\"' Name of the CSV File
strCSVFile="usermod.csv"' *************************************************
' * End Setup
' *************************************************
' Setup ADO Connection to CSV file
SETcn=CREATEOBJECT("ADODB.Connection")SETrs=CREATEOBJECT("ADODB.Recordset")cn.Open"Provider=Microsoft.Jet.OLEDB.4.0;"& _
"Data Source="&strCSVFolder&";"& _
"Extended Properties=""text;HDR=YES;FMT=Delimited"""rs.Open"SELECT * FROM ["&strCSVFile&"]", _
cn,adOpenStatic,adLockOptimistic,adCmdText' Check if search attribute exists
blnSearchAttributeExists=falseFOREACHobjFieldinrs.FieldsIFUCASE(objField.Name)=UCASE(strSearchAttribute)THENblnSearchAttributeExists=trueENDIFNEXTIFblnSearchAttributeExists=falseTHENMSGBOX"'"&strSearchAttribute&"' attribute must be specified in the CSV header."& _
VbCrLf&"The attribute is used to map the data the csv file to users in Active Directory.",vbCriticalwscript.quitENDIF' Read CSV File
DOUntilrs.EOF' Get the ADsPath of the user by searching for a user in Active Directory on the search attribute
' specified, where the value is equal to the value in the csv file.
' e.g. LDAP://cn=user1,cn=users,dc=wisesoft,dc=co,dc=uk
userPath=getUser(strSearchAttribute,rs(strSearchAttribute))' Check that an ADsPath was returned
IFLEFT(userPath,6)="Error:"THENwscript.echouserPathELSEwscript.echouserPath' Get the user object
SETobjUser=GETOBJECT(userpath)userChanges=0' Update each attribute in the CSV string
FOREACHobjFieldinrs.FieldsstrAttribute=objField.Nameoldval=""newval=""' Ignore the search attribute (this is used only to search for the user account)
IFUCASE(strAttribute)<>UCASE(strSearchAttribute)ANDUCASE(strAttribute)<>"NULL"THENnewVal=rs(strAttribute)' Get new attribute value from CSV file
IFISNULL(newval)THENnewval=""ENDIF' Special handling for common-name attribute. If the new value contains
' commas they must be escaped with a forward slash.
IFstrAttribute="cn"THENnewVal=REPLACE(newVal,",","\,")ENDIF' Read the current value before changing it
readAttributestrAttribute' Check if the new value is different from the update value
IFoldval<>newvalTHENwscript.echo"Change "&strAttribute&" from '"&oldVal&"' to '"&newVal&"'"' Update attribute
writeAttributestrAttribute,newVal' Used later to check if any changes need to be committed to AD
userChanges=userChanges+1ENDIFENDIFNEXT' Check if we need to commit any updates to AD
IFuserChanges>0THEN' Allow script to continue if an update fails
ONERRORRESUMENEXTerr.clear' Save Changes to AD
objUser.setinfo' Check if update succeeded/failed
IFerr.number<>0THENwscript.echo"Commit Changes: Failed. "&err.descriptionerr.clearELSEwscript.echo"Commit Changes: Succeeded"ENDIFONERRORGOTO0ELSEwscript.echo"No Changes"ENDIFENDIFuserPath=""rs.MoveNextLOOP' Cleanup
rs.closecn.close' *************************************************
' * End of script
' *************************************************
' *************************************************
' * Functions
' *************************************************
' Reads specified attribute and sets the value for the oldVal variable
SUBreadAttribute(BYVALstrAttribute)SELECTCASELCASE(strAttribute)CASE"manager_samaccountname"' special handling to allow update of manager attribute using sAMAccountName (UserName)
' instead of using the distinguished name
DIMobjManager,managerDN' Ignore error if manager is null
ONERRORRESUMENEXTmanagerDN=objUser.GET("manager")ONERRORGOTO0IFmanagerDN=""THENoldVal=""ELSESETobjManager=GETOBJECT("LDAP://"&managerDN)oldVal=objManager.sAMAccountNameSETobjManager=NothingENDIFCASE"terminalservicesprofilepath"'Special handling for "TerminalServicesProfilePath" attribute
oldVal=objUser.TerminalServicesProfilePathCASE"terminalserviceshomedirectory"'Special handling for "TerminalServicesHomeDirectory" attribute
oldVal=objUser.TerminalServicesHomeDirectoryCASE"terminalserviceshomedrive"'Special handling for "TerminalServicesHomeDrive" attribute
oldVal=objUser.TerminalServicesHomeDriveCASE"allowlogon"' Special handling for "allowlogon" (Terminal Services) attribute
' e.g. 1=Allow, 0=Deny
oldVal=objUser.AllowLogonCASE"password"' Password can't be read, just return ****
oldVal="****"CASEELSEONERRORRESUMENEXT' Ignore error if value is null
' Get old attribute value
oldVal=objUser.GET(strAttribute)ONERRORGOTO0ENDSELECTENDSUB' updates the specified attribute
SUBwriteAttribute(BYVALstrAttribute,newVal)SELECTCASELCASE(strAttribute)CASE"cn"'Special handling required for common-name attribute
DIMobjContainerSETobjContainer=GETOBJECT(objUser.Parent)ONERRORRESUMENEXTobjContainer.MoveHereobjUser.ADsPath,"cn="&newVal' The update might fail if a user with the same common-name exists within
' the same container (OU)
IFerr.number<>0THENwscript.echo"Error changing common-name from '"&oldval&"' to '"&newval& _
"'. Check that the common-name is unique within the container (OU)"err.clearENDIFONERRORGOTO0CASE"terminalservicesprofilepath"'Special handling for "TerminalServicesProfilePath" attribute
objUser.TerminalServicesProfilePath=newValCASE"terminalserviceshomedirectory"'Special handling for "TerminalServicesHomeDirectory" attribute
objUser.TerminalServicesHomeDirectory=newValCASE"terminalserviceshomedrive"'Special handling for "TerminalServicesHomeDrive" attribute
objUser.TerminalServicesHomeDrive=newValCASE"allowlogon"' Special handling for "allowlogon" (Terminal Services) attribute
' e.g. 1=Allow, 0=Deny
objUser.AllowLogon=newValCASE"password"' Special handling for setting password
objUser.SetPasswordnewValCASE"manager_samaccountname"' special handling to allow update of manager attribute using sAMAccountName (UserName)
' instead of using the distinguished name
IFnewVal=""THENobjUser.PutExADS_PROPERTY_CLEAR,"manager",NULLELSEDIMobjManager,managerPath,managerDNmanagerPath=GetUser("sAMAccountName",newVal)IFLEFT(managerPath,6)="Error:"THENwscript.echo"Error resolving manager DN:"&managerPathELSESETobjManager=GETOBJECT(managerPath)managerDN=objManager.GET("distinguishedName")SETobjManager=NOTHINGobjUser.Put"manager",managerDNENDIFENDIFCASEELSE' Any other attribute
' code to update "normal" attribute
IFnewVal=""THEN' Special handling to clear an attribute
objUser.PutExADS_PROPERTY_CLEAR,strAttribute,NULLELSEobjUser.putstrAttribute,newValENDIFENDSELECTENDSUB' Function to return the ADsPath of a user account by searching
' for a particular attribute value
' e.g. LDAP://cn=user1,cn=users,dc=wisesoft,dc=co,dc=uk
FUNCTIONgetUser(BYVALstrSearchAttribute,strSearchValue)DIMobjRootDIMgetUserCn,getUserCmd,getUserRSONERRORRESUMENEXTSETobjRoot=GETOBJECT("LDAP://RootDSE")SETgetUserCn=CREATEOBJECT("ADODB.Connection")SETgetUserCmd=CREATEOBJECT("ADODB.Command")SETgetUserRS=CREATEOBJECT("ADODB.Recordset")getUserCn.open"Provider=ADsDSOObject;"getUserCmd.activeconnection=getUserCngetUserCmd.commandtext="<LDAP://"&objRoot.GET("defaultNamingContext")&">;"& _
"(&(objectCategory=person)(objectClass=user)("&strSearchAttribute&"="&strSearchValue&"));"& _
"adsPath;subtree"SETgetUserRs=getUserCmd.EXECUTEIFgetUserRS.recordcount=0THENgetUser="Error: User account not found"ELSEIFgetUserRS.recordcount=1THENgetUser=getUserRs(0)ELSEgetUser="Error: Multiple user accounts found. Expected one user account."ENDIFgetUserCn.closeENDFUNCTION