Find closest DC via DNS (Perl)

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 Perl code from this site.

# This Perl 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.

# ---------------------------------------------------------------
# Adapted from VBScript code contained in 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 ------
my $strDomain = "<DomainDNSName>";  # e.g. emea.rallencorp.com
my $strSite   = "<SiteName>";       # e.g. Default-First-Site-Name (leave blank for any)
my $strDNSServer = "<DNSServer>"; # must be running the W2K DNS server
# ------ END CONFIGURATION ---------
use Win32::OLE;
$Win32::OLE::Warn = 3;
my $objDNS = Win32::OLE->GetObject("winmgmts:\\\\$strDNSServer\\root\\MicrosoftDNS");
my $strOwner;
if ($strSite = "") {
   $strOwner = "_ldap._tcp." . $strDomain;
}
else {
   $strOwner = "_ldap._tcp." . $strSite . "._sites." . $strDomain;
}
my $objRRs = $objDNS->ExecQuery("Select * from MicrosoftDNS_SRVType " .
                                " Where OwnerName = '$strOwner'");
print "Closest Domain Controller(s) for " . $strDomain;
foreach my $objRR (in objRRs) {
   print " ", $objRR->DomainName, "\n";
}

This code has been viewed 1598 times.

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