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
Next


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
'wscript.quit

'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
adoRecordset.MoveFirst

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


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

http://www.petri.co.il/list_all_users_and_groups_in_domain.htm

No comments:

Post a Comment