VBScript to find all DC's in a Active Directory

Sometimes you need to locate all DC's in a domain. A common approach is to check the "Domain Controllers" OU in the domain but this can be inaccurate (a denoted DC can still be present in this container).

The following VBScript parses AD after the nTDSDSA object (Directory Service Agent):
On Error Resume Next
Const ADS_SCOPE_SUBTREE = 2
Set objRootDSE = GetObject("LDAP://RootDSE")
strConfigurationNC = objRootDSE.Get("configurationNamingContext")
Set objConnection = CreateObject("ADODB.Connection")
Set objCommand =   CreateObject("ADODB.Command")
objConnection.Provider = "ADsDSOObject"
objConnection.Open "Active Directory Provider"
Set objCommand.ActiveConnection = objConnection
objCommand.Properties("Page Size") = 1000
objCommand.Properties("Searchscope") = ADS_SCOPE_SUBTREE
objCommand.CommandText = _
    "SELECT ADsPath FROM 'LDAP://" & strConfigurationNC & "' WHERE objectClass='nTDSDSA'" 
Set objRecordSet = objCommand.Execute
objRecordSet.MoveFirst
Do Until objRecordSet.EOF
    Set objParent = GetObject(GetObject(objRecordset.Fields("ADsPath")).Parent)
    WScript.Echo objParent.name
    objRecordSet.MoveNext
Loop

Links

No comments: