Platform SDK: Active Directory, ADSI, and Directory Services

ADS Namespaces Container

At the top of the Active Directory™ tree, above any of the directory providers, is the Namespaces container, which implements the IADsNamespaces COM interface. If you need to write a script that must operate in more than one environment, the Namespaces container will allow your script access to directory services in a way that is completely independent of the namespace provider. Binding to the Namespaces container first allows the same script access to WinNT, LDAP, NDS or other providers without having to write a separate script for each.

To bind to the Namespaces container, use the following syntax:

Set myObj = GetObject("ADs:")

The following script lists all the namespace providers installed on a machine:

Dim myADS
Dim member

Set myADS = GetObject("ADs:")

For Each member In myADS
    WScript.Echo member.Name
Next

From here, it is possible to find the domains within each namespace. The following script enumerates the Namespaces container to find out what providers are available, then it enumerates each provider namespace to return the domains available under that namespace:

Dim myADS
Dim namespace
Dim domain

Set myADS = GetObject("ADs:")

On Error Resume Next
For Each namespace In myADS
    WScript.Echo "Domains in " & namespace.Name
    For Each domain In namespace
        If Err.Number = &H800704B8 Then
            WScript.Echo "    This namespace contains no domains"
        Elseif Err.Number <> 0 Then
            WScript.Echo "Unexpected error: " & Err.Number
            WScript.Echo Err.Description
            WScript.Quit(1)
        Else
            WScript.Echo "    " & domain.Name
        End If
    Next
Next

Notice the use of On Error Resume Next in the example. If a namespace does not contain any domains, ADSI will return the error 800704B8 (an "Extended Error") and stop execution of the script. The use of On Error, and If Err.Number later in the script, allows the code to continue enumerating other provider's namespaces without stopping if one of them contains no domains. See Errors and Error Trapping for more information about trapping ADSI errors.