Find DCs and GCs in a site (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 prints the domain controllers in a site and then
' prints the global catalog servers in the site

' ---------------------------------------------------------------
' 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 ------
strSite   = "<SiteName>"       ' e.g. Default-First-Site-Name
strForest = "<ForestDNSName>"  ' e.g. rallencorp.com                 
' ------ END CONFIGURATION ---------

set objRootDSE = GetObject("LDAP://" & strForest & "/RootDSE")
strADsPath =  "<LDAP://cn=servers,cn=" & strSite & ",cn=sites," & objRootDSE.Get("configurationNamingContext") & ">;"
strFilter  = "(objectcategory=ntdsdsa);"
strAttrs   = "distinguishedName;"
strScope   = "SubTree"

WScript.Echo "Domain controllers in " & strSite & ":"
set objConn = CreateObject("ADODB.Connection")
objConn.Provider = "ADsDSOObject"
objConn.Open "Active Directory Provider"
set objRS = objConn.Execute(strADsPath & strFilter & strAttrs & strScope)
objRS.MoveFirst
while not objRS.EOF
    Set objNTDS = GetObject("LDAP://" & objRS.Fields(0).Value)
    Set objServer = GetObject( objNTDS.Parent )
    Wscript.Echo " " & objServer.Get("dNSHostName")
    objRS.MoveNext
wend

' Global Catalog filter
strFilter  = "(&(objectcategory=ntdsdsa)(options=1));"
WScript.Echo ""
WScript.Echo "Global Catalogs in " & strSite & ":"
set objRS = objConn.Execute(strADsPath & strFilter & strAttrs & strScope)
objRS.MoveFirst
while not objRS.EOF
    set objNTDS = GetObject("LDAP://" & objRS.Fields(0).Value)
    set objServer = GetObject( objNTDS.Parent )
    Wscript.Echo " " & objServer.Get("dNSHostName")
    objRS.MoveNext
wend

This code has been viewed 2461 times.

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