Find closest DC via DNS (VBScript)

This code can be found in Chapter 3 of Active Directory Cookbook, 2nd edition

Purchase XP Cookbook or Networking Recipes for only $25 plus shipping! While supplies last.

Find out how to download all of the VBScript code from this site.

' This VBScript code finds the closest domain controller in the specified domain
' to the computer the script is run from.  
' If strSite is set to a value, a domain controller in that site will be 
' returned, otherwise any site will be used.

' ---------------------------------------------------------------
' From the book "Active Directory Cookbook" by Robbie Allen
' Publisher: O'Reilly and Associates
' ISBN: 0-596-00466-4
' Book web site: http://rallenhome.com/books/adcookbook/code.html
' ---------------------------------------------------------------

' ------ SCRIPT CONFIGURATION ------
strDomain = "<DomainDNSName>"  ' e.g. emea.rallencorp.com
strSite   = "<SiteName>" ' e.g. Default-First-Site-Name (leave blank for any)
' ------ END CONFIGURATION ---------

set objDNS = GetObject("winMgmts:root\MicrosoftDNS")
if strSite = "" then
   strOwner = "_ldap._tcp." & strDomain
else
   strOwner = "_ldap._tcp." & strSite & "._sites." & strDomain
end if
set objRRs = objDNS.ExecQuery("Select * from MicrosoftDNS_SRVType " & _
                             " Where OwnerName = '" & strOwner & "'")
WScript.Echo "Closest Domain Controller(s) for " & strDomain
for each objRR in objRRs
   Wscript.Echo " " & objRR.DomainName
next

This code has been viewed 2721 times.

New from the creators of TechTasks.com: StatSheet.com