How Can I Enumerate All the Objects in an Active Directory OU?

Hey, Scripting Guy! Question

Hey, Scripting Guy! How can I enumerate all the objects in an Active Directory OU?

— RB

SpacerHey, Scripting Guy! AnswerScript Center

Hey, RB. By the way, thanks: it’s always nice to get an easy question every once in awhile! Enumerating all the objects in an OU is almost embarrassingly-simple: by default, any time you bind to an OU using ADSI you automatically get back a collection of all the objects in that OU. To enumerate those objects, all you have to do is create a For Each loop that walks through the collection.


Don’t believe us? Well, here’s a script that binds to the Servers OU in a domain named fabrikam.com. After making the connection, the script enters a For Each loop that displays the CN (common name) of every item in that collection, and thus every object in the OU:

Set colItems = GetObject _
(“LDAP://ou=Servers, dc=fabrikam, dc=com”)

For Each objItem in colItems
Wscript.Echo objItem.CN
Next


It really is that simple. To adapt this script for use in your domain, just change the binding string accordingly. For example, suppose you want to connect to the Finance OU in contoso.com. Your script would look like this:

Set colItems = GetObject _
(“LDAP://ou=Finance, dc=contoso, dc=com”)

For Each objItem in colItems
Wscript.Echo objItem.CN
Next


Two things to keep in mind here. First, remember that neither Users nor Computers (the default locations for user and computer accounts) are actually OUs; technically, these two entities are known as “containers.” That means you can’t bind to either of these containers using a binding string like thus:

ou=Users, dc=fabrikam, dc=com

That’s not going to work. Instead, you’ll have to reference the CN, like so:

cn=Users, dc=fabrikam, dc=com

Second, there will often be times when you want to enumerate only a subset of items found in an OU; for example, you might want to get back a list of just the user accounts or just the computer accounts. To do that, bind to the OU, then add a filter. For example, this script returns only a list of the computer objects found in the Servers OU. How do we know that it returns only computer objects? Note the Filter, which specifies just one item: Computer.

Set colItems = GetObject _
(“LDAP://ou=Servers, dc=fabrikam, dc=com”)
colItems.Filter = Array(“Computer”)

For Each objItem in colItems
Wscript.Echo objItem.CN
Next


Notice, too, that items included in the Filter have to be passed as an array, even if (as is the case here) you’re only filtering on one thing. Because items are passed as an array, this means you can filter on multiple items. Need a script that returns both user and computer accounts? All you had to do was ask:

Set colItems = GetObject _
(“LDAP://ou=Servers, dc=fabrikam, dc=com”)
colItems.Filter = Array(“User”, “Computer”)

For Each objItem in colItems
Wscript.Echo objItem.CN
Next