Austin Murtha sent me an email with a script question.
His problem was a script that enumerates users and their OU’s.
I have created the script below to help him.
What the script does:
- create a “disconnected recordset” (for the sorting stuff)
- get all users from active directory with an ADO query
- remove undesired results (if instr…)
- add the rest to the disconnected recordset
- sort the recordset
- output to the screen
Follow the next steps to run the script (no admin rights needed):
- copy and paste the script below into the editor (you can use the icons in the upper rights corner of the code)
- save the script (for example c:\temp\usersinou.vbs)
- open a command prompt
- go to “c:\temp”
- give “cscript usersinou.vbs” (without quotes) and enter
The script:
' Name : usersinou.vbs
' Description : script to enumerate all Active Directory users sorted by OU
' Author : dirk adamsky - deludi bv
' Version : 1.0
' Date : 05-10-2011
Set DataList = CreateObject("ADOR.Recordset")
DataList.Fields.Append "Name", 200, 255
DataList.Fields.Append "OU", 200, 255
DataList.Open
Set adoCommand = CreateObject("ADODB.Command")
Set adoConnection = CreateObject("ADODB.Connection")
adoConnection.Provider = "ADsDSOObject"
adoConnection.Open "Active Directory Provider"
adoCommand.ActiveConnection = adoConnection
Set objRootDSE = GetObject("LDAP://RootDSE")
strBase = ""
strFilter = "(&(objectCategory=person)(objectClass=user))"
strAttributes = "name,distinguishedname"
strQuery = strBase & ";" & strFilter & ";" & strAttributes & ";subtree"
adoCommand.CommandText = strQuery
adoCommand.Properties("Page Size") = 100
adoCommand.Properties("Timeout") = 30
adoCommand.Properties("Cache Results") = False
Set adoRecordset = adoCommand.Execute
Do Until adoRecordset.EOF
If Instr(adoRecordset.Fields("distinguishedname").Value,"OU=") > 1 Then
DataList.AddNew
DataList("Name") = adoRecordset.Fields("name").Value
DataList("OU") = Mid(adoRecordset.Fields("distinguishedname").Value, Instr(adoRecordset.Fields("distinguishedname").Value,"OU="))
Datalist.Update
End If
adoRecordset.MoveNext
Loop
adoRecordset.Close
adoConnection.Close
Set adoRecordset = Nothing
Set objRootDSE = Nothing
Set adoConnection = Nothing
Set adoCommand = Nothing
DataList.Sort = "OU DESC"
DataList.MoveFirst
Do Until DataList.EOF
Wscript.Echo DataList.Fields.Item("OU") & " ; " & DataList.Fields.Item("Name")
DataList.MoveNext
Loop
Datalist.Close
Set DataList = Nothing
When you have a modified version or problems/questions that you want to share please post it at the comments below.
Happy scripting.
Dirk Adamsky
