I have scripted a LDAP (Lightweight Directory Access Protocol) query to demonstrate how to return multiple Active Directory objects in an OU or container that you specify. The script uses an OU argument and a filter to select users who match a sAMAccountName parameter, defines a list of attributes required, positions to the first record, and outputs a semi-colon (;) delimited file 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:\util\GetUsersOU.vbs "OU=OU_TEST,DC=JSIINC,DC=COM" *

To display all the users in the Users container:

cscript //nologo c:\util\GetUsersOU.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:\util\GetUsersOU.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, OU
Dim strFilter, strQuery, objRecordSet, objArgs
Set objArgs = Wscript.Arguments
if objArgs.Count "
'Define the filter elements
strFilter = "(&(objectCategory=person)(objectClass=user)(sAMAccountName=" & sam & "))"
'List all attributes you will require
strAttributes = "distinguishedName,sAMAccountName,givenName,sn,userPrincipalName"
'compose query
strQuery = strBase & ";" & strFilter & ";" & strAttributes & ";subtree"
objCommand.CommandText = strQuery
objCommand.Properties("Page Size") = 99999
objCommand.Properties("Timeout") = 300
objCommand.Properties("Cache Results") = False
Set objRecordSet = objCommand.Execute
Do 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 <div class="Contentquote"><center>" & strDN & </center></div>;<div class="Contentquote"><center> & strSA & </center></div>;<div class="Contentquote"><center> & strUN & </center></div>;<div class="Contentquote"><center> & strGN & </center></div>;<div class="Contentquote"><center> & strsn  & </center></div>"
' Clean up.
Set objConnection = Nothing
Set objCommand = Nothing
Set objRecordSet = Nothing