Targeting Active Directory objects (users, computers, etc)
Here’s a great example of how to do something to every user, computer, or other object in the directory. This enumerates through every object, recursing the entire directory.
- '
- ' ScriptingAnswers.com Essentials - by Don Jones
- '
- ' Targeting AD
- ' This shows how to target every user, computer,
- ' or OU in AD and do something to each. You
- ' just pop your code into the DoObject subroutines.
- 'connect to the root of AD
- Dim rootDSE, domainObject
- Set rootDSE=GetObject("LDAP://RootDSE")
- domainContainer = rootDSE.Get("defaultNamingContext")
- Set oDomain = GetObject("LDAP://" & domainContainer)
- 'start with the domain root
- WorkWithObject oDomain
- Sub DoObject_User(strName)
- 'your code goes here - strName
- 'is a user name. If you don't care
- 'about users, just leave this empty.
- End Sub
- Sub DoObject_Computer(strName)
- 'your code goes here - strName
- 'is a computer name. If you don't care
- 'about computers, just leave this empty.
- End Sub
- Sub WorkWithObject(oContainer)
- Dim oADObject
- For Each oADObject in oContainer
- Select Case oADObject.Class
- Case "user"
- 'oADObject represents a USER object;
- 'do something with it
- DoObject_User oADObject.cn
- Case "computer"
- 'oADObject represents a COMPUTER object;
- 'do something with it
- DoObject_Computer oADObject.cn
- Case "organizationalUnit" , "container"
- 'oADObject is an OU or container…
- 'go through its objects
- WorkWithObject(oADObject)
- End select
- Next
- End Sub
You’ll notice two subroutines, DoObject_User and DoObject_Computer. Just put your code in there. Inside those subroutines, the variable strName contains the name of the current directory object so that you can do something with it.
You can have your script start elsewhere - just change the second LDAP query to something like Set oDomain = GetObject(”LDAP://ou=Sales,dc=domain,dc=com”) and it’ll start with that OU (for example) rather than the root of the domain.
Tags: active directory, ad, computers, Enumerate, users, VBScript Scripts










