How to get a list of all users in an OU (VBScript)

Hi all, welcome back,

Today I'll post a very straight forward sample which gets a list of all users in an Organizational Unit (OU) in Active Directory (AD) using VBScript:

 ' Get OU
'
strOU = "OU=Users,DC=domain,DC=com"

' Create connection to AD
'
Set objConnection = CreateObject("ADODB.Connection")
objConnection.Open "Provider=ADsDSOObject;"

' Create command
'
Set objCommand = CreateObject("ADODB.Command")
objCommand.ActiveConnection = objConnection
objCommand.Properties("Page Size") = 1000

' Execute command to get all users in OU
'
objCommand.CommandText = _
  "<LDAP://" & strOU & ">;" & _
  "(&(objectclass=user)(objectcategory=person));" & _
  "adspath,distinguishedname,sAMAccountName;subtree"
Set objRecordSet = objCommand.Execute

' Show info for each user in OU
'
Do Until objRecordSet.EOF

  ' Show required info for a user
  '  
  WScript.Echo objRecordSet.Fields("adspath").Value
  WScript.Echo objRecordSet.Fields("distinguishedname").Value
  WScript.Echo objRecordSet.Fields("sAMAccountName").Value

  ' Move to the next user
  '
  objRecordSet.MoveNext

Loop

' Clean up
'
objRecordSet.Close
Set objRecordSet = Nothing
Set objCommand = Nothing
objConnection.Close
Set objConnection = Nothing

 

I hope this helps.

Regards,

 

Alex (Alejandro Campos Magencio)