How Can I Get a List of All the Domains in a Forest?

How Can I Get a List of All the Domains in a Forest?

  • Comments 1
  • Likes
Hey, Scripting Guy! Question

Hey, Scripting Guy! How can I get a list of all the domains in a forest?

-- NS

SpacerHey, Scripting Guy! AnswerScript Center

Hey, NS. Any time you want information about Active Directory your best bet is to go right to the source: simply ask Active Directory to provide you with this information. Here’s a sample script that binds to the global catalog for the domain Fabrikam.com and searches for all the domain objects:

On Error Resume Next

Const ADS_SCOPE_SUBTREE = 2

Set objConnection = CreateObject("ADODB.Connection")
Set objCommand =   CreateObject("ADODB.Command")
objConnection.Provider = "ADsDSOObject"
objConnection.Open "Active Directory Provider"
Set objCommand.ActiveConnection = objConnection

objCommand.Properties("Page Size") = 1000
objCommand.Properties("Searchscope") = ADS_SCOPE_SUBTREE 

objCommand.CommandText = _
    "SELECT Name FROM 'GC://dc=fabrikam, dc=com' WHERE objectCategory='domain'"  
Set objRecordSet = objCommand.Execute

objRecordSet.MoveFirst
Do Until objRecordSet.EOF
    Wscript.Echo objRecordSet.Fields("Name").Value
    objRecordSet.MoveNext
Loop

If you’ve had some experience with Active Directory search scripts this particular piece of code should look very familiar; if you haven’t had much (or any) experience with Active Directory search scripts we recommend you take a look at the Scripting Guys “Poking Your Nose into Active Directory” webcast. (And it’s worth doing, too, simply because searching Active Directory is such a powerful and useful tool. Besides, Scripting Guys webcasts are always worth watching!)

The only thing to be careful of occurs when we bind to Active Directory. Because we want to search the global catalog we need to use the global catalog provider. Thus instead of specifying LDAP: in our binding string we specify GC:, like so:

"SELECT Name FROM 'GC://dc=fabrikam, dc=com' WHERE objectCategory='domain'"

Other than that, however, this is a pretty straightforward little script, and should return a list of all the domains in your forest.

Your comment has been posted.   Close
Thank you, your comment requires moderation so it may take a while to appear.   Close
Leave a Comment