Thursday, September 10, 2009

VB Scripting - List All users in Domain

Here is a VB Script I Wrote to list all users in a domain. Replace domainname with your domain such as "company.local".

Option Explicit
Dim objDomain, objObject, strFullName, strUserName
Set objDomain = GetObject("WinNT://domainname")
For Each objObject in objDomain
If objObject.Class = "User" Then
strFullName = objObject.FullName
strUserName = objObject.Name
WScript.Echo strFullName & ", " & strUserName
End If

To run it open up a command prompt window and type "cscript listusers.vbs" provided listusers.vbs is the name of your script.

To save it to a csv file which you can then open in excel type:

cscript listusers.vbs > c:\users.csv

This can also be done using LDAP instead of WINNT for example:

'Setup ADO objects
Set adoCommand = CreateObject("ADODB.Command")
Set adoConnection = CreateObject("ADODB.Connection")
adoConnection.Provider = "ADsDSOObject"
adoConnection.Open "Active Directory Provider"
adoCommand.ActiveConnection = adoConnection

'Search Entire Active Direcotry domain
Set objRootDSE = GetObject("LDAP://RootDSE")
strDNSDomain = objRootDSE.Get("DefaultNamingContext")
strBase = ""

'Filter on user objects
strFilter = "(&(objectClass=user)(objectCategory=person))"

'Comma delimited list of attribute values to retrieve
strAttributes = "sAMAccountName"

'Construct the LDAP syntax query
strQuery = strBase & ";" & strFilter & ";" & strAttributes & ";subtree"
wscript.echo strquery

'Properties of the query
adoCommand.CommandText = strQuery
adoCommand.Properties("Page Size") = 100
adoCommand.Properties("Timeout") = 30
adoCommand.Properties("Cache Results") = False

'Run the query
Set adoRecordset = adoCommand.Execute

'Move to the start of the recordset

'Enumerate the resulting recordset
Do Until adoRecordset.EOF
'Retrieve values and display
strName = adoRecordset.Fields("sAMAccountName").Value
WScript.Echo strName

There are also lots of other methods for achieving this... a good site is:

No comments:

Post a Comment