JSI Tip 9843. How can I use VBScript to return all the users in my domain?
Jerold Schulman
October 24, 2005
1 Min Read
I have scripted a LDAP (Lightweight Directory Access Protocol) query to demonstrate how to return multiple Active Directory objects in your domain. The script determines your domain name, employs 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.
NOTE: See tip 10015 How can I use VBScript to return all the users in an OU (Organizational Unit)?
GetUsers.vbs contains:
On Error Resume NextDim objConnection, objCommand, objRootDSE, strDNSDomainDim strFilter, strQuery, objRecordSet, objArgsSet objArgs = Wscript.Argumentsif objArgs.Count = 0 then Wscript.Echo "sAMAccountName argument required. ""*"" or ""J*"" or etc.." WScript.Quit (1)End Ifsam = objArgs(0)Set objConnection = CreateObject("ADODB.Connection")Set objCommand = CreateObject("ADODB.Command")objConnection.Provider = "ADsDSOOBject"objConnection.Open "Active Directory Provider"Set objCommand.ActiveConnection = objConnectionSet objRootDSE = GetObject("LDAP://RootDSE")'Get domainstrDNSDomain = objRootDSE.Get("defaultNamingContext")strBase = ""'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 objRootDSE = NothingSet objRecordSet = Nothing
About the Author
Sign up for the ITPro Today newsletter
Stay on top of the IT universe with commentary, news analysis, how-to's, and tips delivered to your inbox daily.
You May Also Like