How can I use VBScript to return all the users in an OU (Organizational Unit)?
JSI Tip 10015
December 28, 2005
I have scripted a LDAP(Lightweight Directory Access Protocol) query to demonstrate how to return multiple Active Directoryobjects in an OU or container that you specify. The script uses an OU argument and a filter to select users who matcha sAMAccountName parameter,defines a list of attributes required, positions to the first record, and outputs a semi-colon (;) delimitedfile containing the distinguishedName, sAMAccountName, userPrincipalName, givenName, and sn attributes.
To use the GetUsersOU.vbs sample VBScript, see the following examples:
To display all the users in the OU_TEST,DC=JSIINC,DC=COM OU:
cscript //nologo c:utilGetUsersOU.vbs "OU=OU_TEST,DC=JSIINC,DC=COM" *
To display all the users in the Users container:
cscript //nologo c:utilGetUsersOU.vbs "CN=Users,DC=JSIINC,DC=COM" "*"
To display all the users in the domain whose user name (sAMAccountName) begins with a J:
cscript //nologo c:utilGetUsersOU.vbs "DC=JSIINC,DC=COM" "J*"
NOTE: See tip 9843 How can I use VBScript to return all the users in my domain?
GetUsersOU.vbs contains:
Dim objConnection, objCommand, OUDim strFilter, strQuery, objRecordSet, objArgsSet objArgs = Wscript.Argumentsif objArgs.Count "'Define the filter elementsstrFilter = "(&(objectCategory=person)(objectClass=user)(sAMAccountName=" & sam & "))"'List all attributes you will requirestrAttributes = "distinguishedName,sAMAccountName,givenName,sn,userPrincipalName"'compose querystrQuery = strBase & ";" & strFilter & ";" & strAttributes & ";subtree"objCommand.CommandText = strQueryobjCommand.Properties("Page Size") = 99999objCommand.Properties("Timeout") = 300objCommand.Properties("Cache Results") = FalseSet objRecordSet = objCommand.ExecuteobjRecordSet.MoveFirstDo Until objRecordSet.EOF strDN = objRecordSet.Fields("distinguishedName") strGN = objRecordSet.Fields("givenName") strsn = objRecordSet.Fields("sn") strSA = objRecordSet.Fields("sAMAccountName") strUN = objRecordSet.Fields("userPrincipalName") Wscript.Echo
" & strDN &
;
& strSA &
;
& strUN &
;
& strGN &
;
& strsn &
" objRecordSet.MoveNextLoop' Clean up.objConnection.CloseSet objConnection = NothingSet objCommand = NothingSet objRecordSet = Nothing
About the Author
You May Also Like