Finding the Closest Domain Controller

The DC locator process as described in MS KB 314861 and MS KB 247811 defines how clients find the closest domain controller. The process uses the site topology stored in Active Directory to calculate the site where a particular client is. After the client site has been identified, it is a matter of finding a domain controller that is either a member of that same site or that is covering that site.

The Microsoft DsGetDcName Directory Services API method implements the DC Locator process, but unfortunately cannot be used directly from a scripting language, such as VBScript. The IADsTools interface provides a wrapper around DsGetDcName, which is what I used. The nltest /dsgetdc command is also a wrapper around the DsGetDcName method, and is a handy tool when troubleshooting client issues related to finding an optimal domain controller.

Using a command-line interface

The following command finds the closest domain controller in the specified domain (). By default, it will return the DC closest to the computer nltest is being run from, but you can optionally use the /server option to target a remote computer. You can also optionally specify the /site option to find a domain controller that belongs to a particular site.

> nltest /dsgetdc: [/site:] [/server:]

Using VBScript

' This code finds the closest domain controller in the domain
 ' that the computer running the script is in.
 ' ------ SCRIPT CONFIGURATION ------
 strDomain = ""  ' e.g., emea.rallencorp.com
 ' ------ END CONFIGURATION ---------
set objIadsTools = CreateObject("IADsTools.DCFunctions")
 objIadsTools.DsGetDcName( Cstr(strDomain) )
 Wscript.Echo "DC: " & objIadsTools.DCName
 Wscript.Echo "DC Site: " & objIadsTools.DCSiteName
 Wscript.Echo "Client Site: " & objIadsTools.ClientSiteName