VBScript for AD users?

335 pts.
Active Directory
Active Directory Users and Computers
I need a VBScript that can read the First Name, Last Name, and Email ID properties of Active Directory users from Active Directory. I also need to populate this data onto a text file. Does anyone know the code or a link where I can find this code?
ASKED: April 27, 2010  6:30 PM
UPDATED: April 28, 2010  2:40 PM

Answer Wiki

Thanks. We'll let you know when a new response is added.

You can use ldifde utility that comes already installed in your domain controller.

Here’s a link you can use to get an understanding of the tool:


Link to script found:


Discuss This Question: 1  Reply

There was an error processing your information. Please try again later.
Thanks. We'll let you know when a new response is added.
Send me notifications when members answer or reply to this question.

REGISTER or login:

Forgot Password?
By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy
  • IronHedge
    You could try any of these see how you go, I havent tried them but you can test them (Serveral Scripts): How I do it is use a program called Active User Manager by Mikey Magic Technologies its free and can do almost anything for server 2003 server 2008 (tested and working) "Script1" ' CREATE NEW USER ACCOUNTS Script ' Created by: Rene` Engelhardt ' Last modified: 04 April 2006 ' This script will automatically create new AD accounts based ' on the information contained in the input file. ' Input file must be in the format: <userid>,<firstname>,<surname> ' ----------------------------------------------------------------- Dim objRootDSE, objContainer, objUser, objFileSys Dim strDomainOU, strRtn, strUserID, strFirstname, strSurname Dim strInputFile, strInputData, strData ' EDIT BELOW HERE >>> ' ----------------------------- strInputFile = "data.csv" '<-- This is the path to the input csv file. ' No path indicates file is in same directory as script. strDomainOU = "OU=Year6" '<-- Set the OU/CN here. ' DO NOT EDIT BELOW HERE <<< ' -------------------------------- ' Check just to make sure that the user wants to add the accounts. strRtn = msgbox("Please check the following before continuing:" & chr(10) & chr(10) & _ " - Your users will be added to the OU: " & strDomainOU & chr(10) & _ " - Your input file (which contains the new users) is located at: " & strInputFile & chr(10) & _ " - The input file is in the format:" & chr(10) & _ " <userid>,<firstname>,<surname>" & chr(10) & chr(10) & _ "Are you sure you want to continue?", vbYesNo + vbExclamation, "Proceed to create new accounts?") If strRtn = vbNo Then msgbox "No accounts were created.", vbOkOnly + vbExclamation, "User Cancelled Script" Wscript.Quit End If ' Establish an LDAP connection to a DC and open the input file. Set objRootDSE = GetObject("LDAP://rootDSE") Set objContainer = GetObject("LDAP://" & strDomainOU & "," & objRootDSE.Get("defaultNamingContext")) Set objFileSys = Wscript.CreateObject("Scripting.FileSystemObject") ' Read the contents of the input file and put each line in the file into an array. Set oInputFile = objFileSys.OpenTextFile(strInputFile) strInputData = Split(oInputFile.ReadAll, vbNewline) ' Loop through the array (which contains each line of the file) On Error Resume Next For each strData In strInputData ' Split up the line strUserID= Ucase(split(strData, ",") (0)) strFirstname = Lcase(split(strData, ",") (1)) strFirstname = Ucase(left(strFirstname, 1)) & mid(strFirstname, 2, len(strFirstname)) strSurname = Lcase(split(strData, ",") (2)) strSurname = Ucase(left(strSurname, 1)) & mid(strSurname, 2, len(strSurname)) strSurname = Replace(strSurname, "'", "") ' Create an account for the user Set objUser = objContainer.Create("user", "CN=" & strUserID) objUser.Put "samAccountName", strUserID objUser.Put "userPrincipalName", strUserID objUser.Put "sn", strSurname objUser.Put "givenName", strFirstName objUser.Put "displayName", strFirstname & " " & strSurname objUser.SetInfo ' Set the user's password to their firstname and make sure they are forced to change it objUser.SetPassword lcase(strPassword) objUser.AccountDisabled = False objUser.Put "pwdLastSet", CLng(0) ' Comment out if you don't want to force the user to change password on first logon. objUser.SetInfo Set oUser = Nothing If Err.Number > 0 then msgbox "The following error occurred while trying to create an account for the user " & strUserID & chr(13) & chr(13) & _ "Error Number: " & Err.Number & chr(13) & _ "Error Description: " & Err.Description,vbOkOnly + vbCritical, "Error Occurred" Err.Number = 0 End If Next ' Tell the user the script has finished. msgbox "The script has finished creating your user accounts!",vbOkOnly + vbInformation, "Finished" Set objFileSys = Nothing Set objContainer = Nothing Set objRootDSE = Nothing "Script2" ' CreateUserList3.vbs ' VBScript program to create a Microsoft Excel spreadsheet documenting ' all users in the domain. ' ' ---------------------------------------------------------------------- ' Copyright (c) 2002 Richard L. Mueller ' Hilltop Lab web site - http://www.rlmueller.net ' Version 1.0 - November 12, 2002 ' Version 1.1 - February 19, 2003 - Standardize Hungarian notation. ' This program enumerates all users in the domain and writes each user's ' LDAP DistinguishedName to a Microsoft Excel spreadsheet. ' ' You have a royalty-free right to use, modify, reproduce, and ' distribute this script file in any way you find useful, provided that ' you agree that the copyright owner above has no warranty, obligations, ' or liability for such use. Option Explicit Dim strExcelPath, adoConnection, adoCommand, objRootDSE, strDNSDomain Dim strFilter, strQuery, adoRecordset, strDN, objExcel, objSheet, k ' Check for required arguments. If (Wscript.Arguments.Count < 1) Then Wscript.Echo "Arguments <FileName> required. For example:" & vbCrLf _ & "cscript CreateUserList3.vbs c:MyFolderUserList3.xls" Wscript.Quit(0) End If ' Spreadsheet file to be created. strExcelPath = Wscript.Arguments(0) ' Bind to Excel object. Set objExcel = CreateObject("Excel.Application") objExcel.Workbooks.Add ' Bind to worksheet. Set objSheet = objExcel.ActiveWorkbook.Worksheets(1) objSheet.Name = "Domain User" objSheet.Cells(1, 1).Value = "User Distinguished Name" ' Use ADO to search the domain for all users. Set adoConnection = CreateObject("ADODB.Connection") Set adoCommand = CreateObject("ADODB.Command") adoConnection.Provider = "ADsDSOOBject" adoConnection.Open "Active Directory Provider" Set adoCommand.ActiveConnection = adoConnection ' Determine the DNS domain from the RootDSE object. Set objRootDSE = GetObject("LDAP://RootDSE") strDNSDomain = objRootDSE.Get("defaultNamingContext") strFilter = "(&(objectCategory=person)(objectClass=user))" strQuery = "<LDAP://" & strDNSDomain & ">;" & strFilter _ & ";distinguishedName;subtree" adoCommand.CommandText = strQuery adoCommand.Properties("Page Size") = 100 adoCommand.Properties("Timeout") = 30 adoCommand.Properties("Cache Results") = False ' Enumerate all users. Write each user's Distinguished Name to the ' spreadsheet. k = 2 Set adoRecordset = adoCommand.Execute Do Until adoRecordset.EOF strDN = adoRecordset.Fields("distinguishedName").Value objSheet.Cells(k, 1).Value = strDN k = k + 1 adoRecordset.MoveNext Loop adoRecordset.Close ' Format the spreadsheet. objSheet.Range("A1:A1").Font.Bold = True objSheet.Select objExcel.Columns(1).ColumnWidth = 80 ' Save the spreadsheet. objExcel.ActiveWorkbook.SaveAs strExcelPath objExcel.ActiveWorkbook.Close ' Quit Excel. objExcel.Application.Quit ' Clean up. adoConnection.Close Set adoConnection = Nothing Set adoCommand = Nothing Set objRootDSE = Nothing Set adoRecordset = Nothing Set objSheet = Nothing Set objExcel = Nothing Wscript.Echo "Done" "Script3" ============================== ' --------------------------------------------------- ' Script: createusers2.vbs ' Input: It uses a CSV file with layout logonname,firstname,lastname,password Option Explicit Dim sCSVFileLocation Dim sCSVFile Dim objFSO Dim objFile Dim strLine Dim strItems Dim oNewUser ' ----------LDAP connection variables---------- Dim oRootLDAP Dim oContainer ' ----------Other variables-------------------- Dim sLogon Dim sFirstName Dim sLastName Dim sDisplayName Dim sPassword Dim nPwdLastSet Dim nUserAccountControl ' Used to enable the account Dim sDomain ' ----------Modify this to match your company's AD domain---------- sDomain="corp.myDomain.com" ' ----------Input file location---------- sCSVFileLocation = "C:myUserBase" ' ----------Full path to input file---------- sCSVFile = sCSVFileLocation&"myusers.csv" ' ----------Commands used to open the CSV file and select all of the records---------- set objFSO = CreateObject("Scripting.FileSystemObject") set objFile = objFSO.OpenTextFile(sCSVFile, 1) ' ----------Create a connection to the Active Directory Users container.---------- Set oContainer = GetObject("LDAP://mycorpdc/OU=Import,dc=corp,dc=myDomain,dc=com") ' ----------Allows processing to continue even if an error occurs (i.e. dup user)---------- on error resume next Do Until objFile.AtEndOfStream ' Reads the values (cells) in the sInputFile file. ' --------- Start creating user account---------- ' Read variable information from the CSV file ' and build everything needed to create the account strLine = objFile.ReadLine strItems = split(strLine,",") sLogon = strItems(0) sFirstName = strItems(1) sLastName = strItems(2) sDisplayName = sFirstName&" "&sLastName sPassword = strItems(3) ' ----------Build the User account---------- Set oNewUser = oContainer.Create("User","cn="&sFirstName&" "&SLastName) oNewUser.put "sAMAccountName",lcase(sLogon) oNewUser.put "givenName",sFirstName oNewUser.put "sn",sLastName oNewUser.put "UserPrincipalName",lcase(SLogon)&"@"&sDomain oNewUser.put "DisplayName",sDisplayName oNewUser.put "name",lcase(sLogon) ' ----------Write this information into Active Directory so we can---------- ' modify the password and enable the user account oNewUser.SetInfo ' ----------Change the users password---------- oNewUser.SetPassword sPassword oNewUser.Put "pwdLastSet", -1 ' ----------Enable the user account---------- oNewUser.Put "userAccountControl", 512 oNewUser.SetInfo Loop objFile.Close ' ----------Used only for debugging---------- 'if err.number = -2147019886 then ' msgbox "User logon " & sLogon & "already exists" 'End If ' --------- End of user account creation---------- "Script4 Welcome to Tech-Geeks.Org Monday, April 02 2007 @ 05:51 AM CDT Add bulk users to W2K Active Directory Monday, March 08 2004 @ 05:13 PM CST Contributed by: tsteele Views: 14464 The following script will read user information from a .csv type file and create user accounts in a Windows 2000/2003 Active Directory. It will also add the users to groups and create home directories. To set the correct permissions on the home directories, you must run the batch file created by this script. Note: This is NOT guaranteed! It worked for me running on a Windows 2000 Domain Controller, but has not been tested beyond that. Copy the following text into a text editor such as Notepad and save with a .vbs extension. -TS '// Name: bulkadduser1.vbs '// Purpose: Create user script from CSV file '// Notes: '// 1. Input file must be comma delimited '// 2. Fields must be in the following order and must not be left blank: '// First Name, Last Name, Password, Group Name, Child OU 1, Child OU 2, Child OU 3, '// SAM Logon, Home Drive, Logon Script, Description, Home Directory '// 3. Must run stupermissions.bat AFTER this script to set permissions on home folders '// 4. Must be member of Domain Admins group to run '// 5. OU's and groups must have been created prior to running this script '// 6. Home Directory must use full USN path, i.e. \SERVERSHAREusername -- system variables are not allowed '// 7. Must change InpFile and batFile to correct drive and path prior to running script '// Define variables Option Explicit Dim oFSO, oTF, oOU, oUser, oGroup, oRoot, oFolder, oPerm, oShell, oExec Dim sCN, sOU1, sOU2, sOU3 Dim aLine, sLine, sLogon, sPass, sGroup, sRoot, sDN, vFlg Dim sFname, sLName, sHomedrive, sLogscript, sDescription, sHomeDir '// Set file names -- replace these with desired files Const InpFile = "T:stuimport.csv" 'Import file Const batFile = "T:stupermissions.bat" 'batch file used for resetting home dir permissions Const ForReading = 1 Const ForWriting = 2 Set oFSO = CreateObject("Scripting.FileSystemObject") Set oTF = oFSO.OpenTextFile(InpFile,ForReading,True) Set oPerm = oFSO.OpenTextFile(batFile,ForWriting,True) Set oShell = CreateObject("WScript.Shell") '// vFlg verifies that required fields are in input file vFlg = True Do While oTF.AtEndOfStream <> True sLine = oTF.ReadLine aLine = split(sline, ",",-1,1) sFname = aLine(0) sLname = aLine(1) '// Sets container name to Last Name, First Name sCN = sLname &", "&sFname sPass = aLine(2) sGroup = aLine(3) sOU1 = aLine(4) sOU2 = aLine(5) sOU3 = aLine(6) sLogon = aLine(7) sHomedrive = aLine(8) sLogscript = aLine(9) sDescription = aLine(10) sHomeDir = aLine(11) If vFlg = True Then If isEmpty(sGroup) Or isEmpty(sOU3) Or isEmpty(sOU2) Or isEmpty(sOU1) Then msgbox "Missing Parameter" & vbCr & _ "First Line must contain:" & vbCr & _ "First Name, Last Name, Password, Group Name, Child OU, Child OU, Root OU," & vbCr & _ "SAM Logon ID, Home Drive, Logon Script, Description, Home Directory",_ vbExclamation, "Add Bulk Users" wscript.Quit Else vFlg = False End If End If '// Call the Create User routine CreateaUser '// Call the add to Group routine Add2Group(sDN) Loop oPerm.Close Msgbox "Script complete." & vbCr & _ "Run stupermissions.bat to set proper permissions on Home folders" _ ,vbInformation, "Add Bulk Users" Set oTF = Nothing Set oFSO = Nothing Set oUser = Nothing Set oGroup = Nothing Set oOU = Nothing Set oRoot = Nothing '//-------------------------- '// Create User subroutine '//-------------------------- Sub CreateaUser() '// Bind to the domain Root Set oRoot = GetObject("LDAP://rootDSE") sRoot = oRoot.Get("defaultNamingContext") '// Bind to the OU where users are to be added Set oOU = GetObject("LDAP://ou=" & sOU1 & ",ou=" & sOU2 & ",ou=" & sOU3 & "," & sRoot) '// Remove comment from following line to enable screen display for debug '// msgbox sCN & "ou=" & sOU1 & ",ou=" & sOU2 & ",ou=" & sOU3 & "," & sRoot Set oUser = oOU.Create("user", "cn=" & sCN) '// Remove comment from following line to enable error check from Create operation for debug '// If err.number<>0 then msgbox err.number On Error Resume Next '// Load fields in AD record oUser.put "sAMAccountName", lcase(sLogon) oUser.put "givenName", sFname oUser.put "sn", sLname oUser.put "UserPrincipalName", lcase(sLogon) oUser.put "DisplayName", sLname &", "&sFname oUser.put "name", sCN oUser.put "homeDrive", sHomedrive oUser.put "scriptPath", sLogscript oUser.put "description", sDescription oUser.put "homeDirectory", sHomeDir oUser.SetInfo '// Test for duplicate User If err.number = -2147019886 then msgbox "User logon for " & sLogon & " already exists." _ ,vbExclamation, "Add Bulk Users" Exit Sub End If '// Set initial password oUser.setpassword sPass oUser.AccountDisabled = False oUser.SetInfo '// Create user home folder Set oFolder = oFSO.CreateFolder(sHomeDir) '// Write line to bat file for cacls command to reset ACL on user home dir oPerm.WriteLine("echo y|cacls "& sHomeDir &" /G "& lcase(sLogon) &":F Administrators:F") '// Set the User's DN for adding to group sDN = oUser.get("DistinguishedName") End Sub '//-------------------------- '// Add to Group subroutine '//-------------------------- Sub Add2Group(Byval sDN) Const ADS_PROPERTY_APPEND = 3 On Error Resume Next '// Test if group is empty If IsEmpty(oGroup) Then Set oGroup = GetObject _ ("LDAP://cn=" & sGroup & ",ou=" & sOU1 & ",ou=" & sOU2 & ",ou=" & sOU3 & "," & sRoot) End If '// Add user to group oGroup.PutEx ADS_PROPERTY_APPEND, _ "member", Array(sDN) oGroup.SetInfo sDN = Nothing '// Test if user is already member of group If err.number <> 0 Then msgbox "User " & sLogon & _ " is already a member of " & sGroup, _ ,vbExclamation, "Add Bulk Users" Exit Sub End If End Sub
    360 pointsBadges:

Forgot Password

No problem! Submit your e-mail address below. We'll send you an e-mail containing your password.

Your password has been sent to:

To follow this tag...

There was an error processing your information. Please try again later.

REGISTER or login:

Forgot Password?
By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy

Thanks! We'll email you when relevant content is added and updated.