Recipe 3.8 Finding the Domain Controllers for a Domain

3.8.1 Problem

You want to find the domain controllers in a domain.

3.8.2 Solution Using a graphical user interface
  1. Open the Active Directory Users and Computers snap-in.

  2. Connect to the target domain.

  3. Click on the Domain Controllers OU.

  4. The list of domain controllers for the domain will be present in the right pane. Using a command-line interface
> netdom query dc /Domain:<DomainDNSName> Using VBScript
' This code displays the domain controllers for the specified domain.
strDomain = "<DomainDNSName>"  ' e.g.
' ------ END CONFIGURATION ---------

set objRootDSE = GetObject("LDAP://" & strDomain & "/RootDSE")
set objDomain = GetObject("LDAP://" & objRootDSE.Get("defaultNamingContext"))
strMasteredBy = objDomain.GetEx("masteredBy")
for each strNTDSDN in strMasteredBy
   set objNTDS = GetObject("LDAP://" & strNTDSDN)
   set objServer = GetObject(objNTDS.Parent)
   Wscript.echo objServer.Get("dNSHostName")

3.8.3 Discussion

There are several ways to get a list of domain controllers for a domain. The GUI solution simply looks at the computer objects in the Domain Controllers OU. Whenever you promote a domain controller into a domain, a computer object for the server gets placed into the Domain Controllers OU off the root of the domain. Some administrators may move their domain controller computer objects to different OUs, so this test does not guarantee accuracy in all cases.

The CLI and VBScript solutions take a slightly different approach by looking at the masteredBy attribute on the domain object (e.g., dc=emea,dc=rallencorp,dc=com) of the domain. The masteredBy attribute contains a list of distinguished names of the nTDSDSA objects of all the domain controllers for that domain. The parent object of the nTDSDSA object, which is the server object of the domain controller, has a dNSHostName attribute that contains the fully qualified DNS name of the server.

And for yet another solution, see Recipe 3.21 to find out how to query DNS to get the list of domain controllers for a domain.

3.8.4 See Also

Recipe 3.21 for finding domain controllers via DNS

    Chapter 3. Domain Controllers, Global Catalogs, and FSMOs
    Chapter 6. Users
    Appendix A. Tool List