Part 5: Scripting DNS on Clients

Domain Name System (DNS) is the primary mechanism for name resolution on most TCP/IP networks, and the default name-resolution protocol for Windows 2000, Windows XP, and Windows Server 2003. Working together with DHCP servers, DNS servers that use DNS dynamic update can now automate many aspects of name resolution that were once handled by manually configured HOSTS files. DNS can also integrate with Active Directory to connect name resolution with directory management.

When clients use DHCP, they can also get DNS configuration from the DHCP server. Figure 10 shows the Internet Protocol [TCP/IP] Properties dialog box (reached through Network Connections), which you can use to specify this setting by clicking the "Obtain DNS server address automatically" radio button. In this case, DHCP helps you automate DNS settings on clients without using scripting.

05ATNC01.gif

Figure 10   Automating DNS Settings on Clients by Using the Windows Interface

Tthe Ipconfig.exe command-line tool can also retrieve DNS client settings and perform tasks like purging the DNS client resolver cache.

There may be situations, however, in which you need to configure DNS clients remotely or in batches — for example, when replacing old DNS servers with new, making changes on servers, or changing subnet arrangements. In such cases, manually configuring each host is not an efficient use of administrative time. Here, as with other TCP/IP protocols, WMI provides methods and properties of the Win32_NetworkAdapterConfiguration class that you can use to automate DNS client configuration.

Note that Win32_ NetworkAdapterConfiguration does not provide a property or method that explicitly corresponds to the "Obtain DNS server address automatically" setting. The DNSServerSearchOrder property displays the IP addresses of any DNS servers configured on the client whether they are set locally or obtained from the DHCP server.

Optionally, you can retrieve or set a value corresponding to "Obtain DNS server address automatically" by using the two registry entries, DhcpNameServer and NameServer, which you can find at the following registry location:

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\Interfaces
\{AdapterIdentifier}

If the value of NameServer is null, the client tries to obtain a DNS server address automatically from the DHCP server. If NameServer contains an IP address as its value, the IP address overrides any DNS server address obtained from the DHCP server. In this case, any value in the DhcpNameServer registry entry does not appear in the dialog box.

WMI also includes a DNS Server provider (first included in the Windows 2000 Resource Kit; now part of the Windows Server 2003 operating system), which enables you to automate server operations with scripting. Information about scripting the DNS Server provider is beyond the scope of this paper.

The command-line tool Dnscmd.exe also offers extensive options for DNS server configuration.

This section provides scripting steps and sample scripts for these tasks:

  • Displaying DNS client information.

  • Enabling DNS.

  • Changing the DNS server search order, the DNS domain, the DNS domain suffix search order, and the DNS registration settings.

On This Page

Displaying DNS Client Information
Enabling DNS
Changing the DNS Server Search Order
Changing the DNS Domain
Changing the DNS Domain Suffix Search Order
Changing Dynamic DNS Registration Settings
Scenario: Changing DNS Servers and Domains
Tools for Scripting DNS on Clients

Displaying DNS Client Information

As with DHCP, when you manage DNS on clients, the first step is usually to determine current settings. Figure 11 shows the DNS tab of the Advanced TCP/IP Settings dialog box, which provides a way to access these settings by using the Windows interface.

05ATNC02.gif

Figure 11   Displaying Current DNS Settings by Using the Windows Interface

For scripts that use WMI, the Win32_NetworkAdapterConfiguration class offers several properties that enable you to script DNS client configuration. Table 13 describes these DNS properties.

Table 13   Win32_NetworkAdapterConfiguration DNS Properties

Property

Type

Description

DNSDomain

String

Organization name followed by a period and an extension that indicates the type of organization, such as microsoft.com. The name can be any combination of the letters A–Z, the numerals 0–9, and the hyphen (-), plus the period (.) character used as a separator.

Example: "microsoft.com"

DNSDomainSuffixSearchOrder

String

Space-delimited list of DNS domain suffixes to be appended to the end of host names during name resolution. When attempting to resolve a fully-qualified domain name (FQDN) from a host only name, the system will first append the local domain name. If this is not successful, the system will use the domain suffix list to create additional FQDNs in the order listed and query DNS servers for each

Example: "samples.microsoft.com example.microsoft.com"

DNSEnabledForWINSResolution

Boolean

If TRUE, the DNS is enabled for name resolution over Windows Internet Name Service (WINS) resolution. If the name cannot be resolved by using DNS, the name request is forwarded to WINS for resolution.

DNSHostName

String

Host name used to identify the local computer for authentication by some utilities. Other TCP/IP-based utilities can use this value to acquire the name of the local computer. Host names are stored on DNS servers in a table that maps names to IP addresses for use by DNS. The name can be any combination of the letters A–Z, the numerals 0–9, and the hyphen (-), plus the period (.) character used as a separator. By default, this value is the Microsoft networking computer name, but the network administrator can assign another host name without affecting the computer name.

Example: "corpdns"

DNSServerSearchOrder

String array

Array of server IP addresses to be used in querying for DNS servers.

DomainDNSRegistrationEnabled

Boolean

If TRUE, the IP addresses for this connection are registered in DNS under the domain name of this connection in addition to being registered under the computer's full DNS name. The domain name of this connection is either set using the SetDNSDomain()method or assigned by DHCP. The registered name is the host name of the computer with the domain name appended. This property is new for Windows XP.

FullDNSRegistrationEnabled

Boolean

If TRUE, the IP addresses for this connection are registered in DNS under the computer's full DNS name. The full DNS name of the computer is displayed on the Network Identification tab in the System application in Control Panel. This property is new for Windows XP.

All the properties in the previous table are read-only.

Table 14 describes the Win32_NetworkAdapterConfiguration methods to use for scripting DNS client configuration.

Table 14   Win32_NetworkAdapterConfiguration DNS Methods

Method

Parameters

Description

EnableDNS

DNSHostName – string
DNSDomain – string
DNSServerSearchOrder – array of strings
DNSDomainSuffixSearchOrder - string

Enables DNS on the client.

SetDNSDomain

DNSDomain – string

Allows for the setting of the DNS domain. This is an instance-dependent method call that applies on a per-adapter basis. In Windows 2000, the setting applies to the targeted adapter. In Windows NT 4.0, this setting is global.

SetDNSServerSearchOrder

DNSServerSearchOrder – array of strings

Uses an array of string elements to set the server search order. To remove all DNS servers from the search order, use Null rather than an empty string. This is an instance-dependent method call that applies on a per-adapter basis. After static DNS servers are specified to start using DHCP instead of static DNS servers, you can call the method without supplying "in" parameters. In Windows 2000, the setting applies to the targeted adapter. In Windows NT 4.0, the setting is global.

SetDNSSuffixSearchOrder

DNSDomainSuffixSearchOrder – string

Static method. Uses an array of string elements to set the suffix search order. For Windows NT only, this is an instance-independent call that applies to all adapters.

SetDynamicDNSRegistration

FullDNSRegistrationEnabled – Boolean
DomainDNSRegistrationEnabled – Boolean

Indicates the mode of dynamic DNS registration of IP addresses for this IP-bound adapter.

All the methods in the previous table return a positive integer:

  • 0 indicates successful completion.

  • 1 indicates successful completion with reboot required.

  • Numbers greater than 1 indicate that some problem was encountered and the method could not complete. The WMI SDK lists the meanings of return values for these methods.

The following script, Dnssettings.vbs, displays the DNS-related settings that are exposed by Win32_NetworkAdapterConfiguration. The DNSEnabledForWINSResolution property, which is meaningful only if NetBIOS name resolution is used, is included instead in the settings script in the WINS section of this paper. On Windows Server 2003, you can also read the host name from the DNSHostName property of the Win32_ComputerSystem class; on older operating systems, this Name property may return the NetBIOS name if it is different from the DNS name, depending on client and network configuration.

Scripting Steps

Listing 28 displays the DNS client settings for each network adapter configuration on a computer.

  1. Create a variable and assign the name of a computer to it. For the local computer, simply specify "." as the computer name. To run this script remotely, specify the name of an accessible remote computer on your network on which you have administrative privileges. The name can be in the form of either a host name or an IP address.

  2. Use a GetObject call to connect to the WMI namespace root\cimv2, and set the impersonation level to “impersonate.”

  3. Use the ExecQuery method to query the Win32_NetworkAdapterConfiguration class, filtering the WQL query with “WHERE IPEnabled = True.”

    This returns a collection consisting of all the network adapter configurations on the computer for which IP is enabled.

  4. For each network adapter configuration in the collection, perform the following tasks.

  5. Assign the Win32_NetworkAdapterConfiguration properties DNSHostName, Index, Description, DNSDomain, DomainDNSRegistrationEnabled and FullDNSRegistrationEnabled to variables.

  6. Iterate through the arrays returned by the DNSDomainSuffixSearchOrder and DNSServerSearchOrder properties and convert them into formatted strings.

  7. Concatenate the variables and labels into a string. On each iteration through another network adapter, concatenate the strings for that adapter on to the original string.

  8. Display the host name and the settings for each adapter.

    Listing 28   Dnssettings.vbs

  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46

On Error Resume Next
 
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
 & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colNicConfigs = objWMIService.ExecQuery _
 ("SELECT * FROM Win32_NetworkAdapterConfiguration WHERE IPEnabled = True")
 
For Each objNicConfig In colNicConfigs
  strDNSSuffixSO = ""
  strDNSServerSO = ""
  strDNSHostName = objNicConfig.DNSHostName
  strIndex = objNicConfig.Index
  strDescription = objNicConfig.Description
  strDNSDomain = objNicConfig.DNSDomain
  strDNSSuffixSO = ""
  If Not IsNull(objNicConfig.DNSDomainSuffixSearchOrder) Then
    For Each strDNSSuffix In objNicConfig.DNSDomainSuffixSearchOrder
      strDNSSuffixSO = strDNSSuffixSO & VbCrLf & String(37, " ") & _
 strDNSSuffix
    Next
  End If
  strDNSServerSO = ""
  If Not IsNull(objNicConfig.DNSServerSearchOrder) Then
    For Each strDNSServer In objNicConfig.DNSServerSearchOrder
      strDNSServerSO = strDNSServerSO & VbCrLf & String(37, " ") & _
 strDNSServer
    Next
  End If
  strDomainDNSRegistrationEnabled = _
 objNicConfig.DomainDNSRegistrationEnabled
  strFullDNSRegistrationEnabled = objNicConfig.FullDNSRegistrationEnabled
  strDNSSettings = strDNSSettings & VbCrLf & VbCrLf & _
   "  Network Adapter " & strIndex & VbCrLf & _
   "    " & strDescription & VbCrLf & VbCrLf & _
   "    DNS Domain:                      " & strDNSDomain & VbCrLf & _
   "    DNS Domain Suffix Search Order:" & strDNSSuffixSO & VbCrLf & _
   "    DNS Server Search Order:" & strDNSServerSO & VbCrLf & _
   "    Domain DNS Registration Enabled: " & _
   strDomainDNSRegistrationEnabled & VbCrLf & _
   "    Full DNS Registration Enabled:   " & _
   strFullDNSRegistrationEnabled
Next
 
WScript.Echo VbCrLf & "DNS Settings" & VbCrLf & VbCrLf & _
 "Host Name: " & strDNSHostName & strDNSSettings

When you use Cscript.exe to run this script, output similar to the following is displayed in the command window:

C:\scripts>dnssettings.vbs

 

DNS Settings

 

Host Name: client1

 

  Network Adapter 1

    3Com 3C920 Integrated Fast Ethernet Controller (3C905C-TX Compatible) - Pack

et Scheduler Miniport

 

    DNS Domain:

    DNS Domain Suffix Search Order:

    DNS Server Search Order:

                                     192.168.0.1

    Domain DNS Registration Enabled:

    Full DNS Registration Enabled:

Enabling DNS

For situations where DNS must be enabled on hosts, for example, when a network is upgraded from another name resolution system such as WINS, Win32_NetworkAdapterConfiguration offers the EnableDNS() method.

The method takes four optional parameters: DNSHostName, DNSDomain, DNSServerSearchOrder, and DNSDomainSuffixSearchOrder. The data types of the first two and the last are strings, of DNSServerSearchOrder, an array of strings.

The Win32_ComputerSystem class includes a Rename() method that also lets you change the computer name. To use the Rename() method, you must be a member of the local administrator group. Note that you cannot use this method to rename remote hosts that are part of a domain. This class also exposes JoinDomainOrWorkgroup() and UnjoinDomainOrWorkgroup() methods. All three methods are new for Windows XP and Windows Server 2003.

Scripting Steps

caution.gif  Caution
This script may make changes in your computer configuration. Run it only on a test computer and note the settings involved before running it.

Listing 29 enables DNS for all network adapters on a computer, configuring the host name to client1, the DNS domain to fabrikam.com, the DNS server search order as 192.168.0.1, 192.168.0.2, and the DNS search order suffixes as fabrikam.com and na.fabrikam.com.

To carry out this task, the script performs the following steps:

  1. Create variables to specify the computer name and parameters to pass to the EnableDNS method.

  2. Use a GetObject call to connect to the WMI namespace root\cimv2, and set the impersonation level to “impersonate.”

  3. Use the ExecQuery method to query the Win32_NetworkAdapterConfiguration class, filtered for instances where IP is enabled.

    This returns a collection consisting of all the network adapter configurations on the computer.

  4. For each network adapter configuration in the collection, perform the following tasks.

  5. Display the index number and description of the network adapter.

  6. Call the EnableDNS method, passing it the variables already initialized with the host name, domain, DNS server search order and DNS domain suffix search order.

  7. Check the value returned by the method, and display a success or error message accordingly.

  8. Requery Win32_NetworkAdapterConfiguration and display the configuration after the operation.

    Listing 29   Dns-enable.vbs

  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51

On Error Resume Next
 
strComputer = "."
strDNSHostName = "client1"
strDNSDomain = "fabrikam.com"
arrDNSServerSearchOrder = Array("192.168.0.1", "192.168.0.2")
arrDNSDomainSuffixSearchOrder = Array("hr.fabrikam.com", "contoso.com")
 
Set objWMIService = GetObject("winmgmts:" _
 & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set objNicConf = objWMIService.Get("Win32_NetworkAdapterConfiguration")
 
WScript.Echo VbCrLf & "DNS Host Name: " & strDNSHostName & VbCrLf & _
 "  Attempting to enable DNS"
intEnableDNS = objNicConf.EnableDNS(strDNSHostName, strDNSDomain, _
 arrDNSServerSearchOrder, arrDNSDomainSuffixSearchOrder)
If intEnableDNS = 0 Then
  WScript.Echo "  Successfully enabled DNS."
ElseIf intEnableDNS = 1 Then
  WScript.Echo "  Successfully enabled DNS." & VbCrLf & "    Must reboot."
Else
  WScript.Echo "  Unable to enable DNS."
End If
 
WScript.Echo VbCrLf & String(80,"-")
 
Set colNicConfigs = objWMIService.ExecQuery _
 ("SELECT * FROM Win32_NetworkAdapterConfiguration WHERE IPEnabled = True")
 
For Each objNicConfig In colNicConfigs
  strDNSHostName = objNicConfig.DNSHostName
Next
WScript.Echo VbCrLf & "DNS Host Name: " & strDNSHostName
 
For Each objNicConfig In colNicConfigs
  WScript.Echo VbCrLf & "  Network Adapter " & objNicConfig.Index & _
 VbCrLf &   "    " & objNicConfig.Description
  WScript.Echo "    DNS Domain: " & objNicConfig.DNSDomain
  WScript.Echo "    DNS Server Search Order:"
  If Not IsNull(objNicConfig.DNSServerSearchOrder) Then
    For Each strDNSServer In objNicConfig.DNSServerSearchOrder
      WScript.Echo "        " & strDNSServer
    Next
  End If
  WScript.Echo "    DNS Domain Suffix Search Order:"
  If Not IsNull(objNicConfig.DNSServerSearchOrder) Then
    For Each strDNSDomainSuffix In objNicConfig.DNSDomainSuffixSearchOrder
      WScript.Echo "        " & strDNSDomainSuffix   
    Next
  End If
Next

When you use Cscript.exe to run this script, output similar to the following is displayed in the command window:

C:\scripts>dns-enable.vbs

 

DNS Host Name: client1

  Attempting to enable DNS

  Unable to enable DNS.

 

--------------------------------------------------------------------------------

 

 

DNS Host Name: client1

 

  Network Adapter 1

    3Com 3C920 Integrated Fast Ethernet Controller (3C905C-TX Compatible) - Pack

et Scheduler Miniport

    DNS Domain:

    DNS Server Search Order:

        192.168.0.1

    DNS Domain Suffix Search Order:

        hr.fabrikam.com

        contoso.com

Changing the DNS Server Search Order

If you do not use DHCP to determine the DNS servers for a client, you can configure each client with a list of one or more DNS servers, in order of priority, to use for DNS name resolution. Win32_NetworkAdapterConfiguration provides a DNSServerSearchOrder property that contains this list in an array of strings, as well as a SetDNSServerSearchOrder method that modifies the property.

For the property and method, the first server on the list is the primary DNS server for the network adapter. Using this method, you can replace the list of DNS servers with a new one, or you can remove or replace one or more members in any position. The scripting techniques to accomplish these changes vary depending on which variation is being performed. To remove all DNS servers from the search order, you must use Null rather than an empty string.

This section provides scripting steps and sample scripts for these tasks:

  • Replacing the entire DNS server search order list.

  • Replacing one DNS server with another DNS server

  • Adding a DNS server to the end or the beginning of the search order.

Replacing the DNS Server Search Order List

If the search order of DNS servers must be changed, the simplest alternative is to replace the entire list with a new search order list.

Scripting Steps

caution.gif  Caution
This script may make changes in your computer configuration. Run it only on a test computer and note the settings involved before running it.

For each network adapter, Listing 30 replaces the current DNS server search order list with a new one.

  1. Create a variable to specify the computer name.

  2. Assign IP addresses to an array representing the new DNS server search order. Note that to remove all DNS servers from the search order, you must use Null rather than an empty string.

  3. Use a GetObject call to connect to the WMI namespace root\cimv2, and set the impersonation level to “impersonate.”

  4. Use the ExecQuery method to query the Win32_NetworkAdapterConfiguration class, filtering the WQL query with “WHERE IPEnabled = True.”

    This returns a collection consisting of all the network adapter configurations on the computer for which IP is enabled.

  5. For each network adapter configuration in the collection, perform the following tasks.

  6. Display the index and current DNS server search order list of the network adapter

  7. Call the SetDNSServerSearchOrder method of the Win32_NetworkAdapterConfiguration class, passing it as a parameter the array of IP addresses representing the new DNS server search order.

  8. Check the value returned by the method, and display a success or error message.

  9. Requery Win32_NetworkAdapterConfiguration and display the new DNS server search order.

    Listing 30   Dns-replaceserverlist.vbs

  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43

On Error Resume Next
 
strComputer = "."
arrNewDNSServerSearchOrder = Array("192.168.0.1", "192.168.0.2")
 
Set objWMIService = GetObject("winmgmts:" _
 & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colNicConfigs = objWMIService.ExecQuery _
 ("SELECT * FROM Win32_NetworkAdapterConfiguration WHERE IPEnabled = True")
 
WScript.Echo VbCrLf & "Computer: " & strComputer
 
For Each objNicConfig In colNicConfigs
  WScript.Echo VbCrLf & "  Network Adapter " & objNicConfig.Index
  WScript.Echo "    DNS Server Search Order - Before:"
  If Not IsNull(objNicConfig.DNSServerSearchOrder) Then
    For Each strDNSServer In objNicConfig.DNSServerSearchOrder
      WScript.Echo "        " & strDNSServer
    Next
  End If
  intSetDNSServers = _
   objNicConfig.SetDNSServerSearchOrder(arrNewDNSServerSearchOrder)
  If intSetDNSServers = 0 Then
    WScript.Echo "    Replaced DNS server search order list."
  Else
    WScript.Echo "    Unable to replace DNS server search order list."
  End If
Next
 
WScript.Echo VbCrLf & String(80, "-")
 
Set colNicConfigs = objWMIService.ExecQuery _
 ("SELECT * FROM Win32_NetworkAdapterConfiguration WHERE IPEnabled = True")
 
For Each objNicConfig In colNicConfigs
  WScript.Echo VbCrLf & "  Network Adapter " & objNicConfig.Index
  WScript.Echo "    DNS Server Search Order - After:"
  If Not IsNull(objNicConfig.DNSServerSearchOrder) Then
    For Each strDNSServer In objNicConfig.DNSServerSearchOrder
      WScript.Echo "        " & strDNSServer
    Next
  End If
Next

When you use Cscript.exe to run this script, output similar to the following is displayed in the command window:

C:\scripts>dns-replaceserverlist.vbs

 

Computer: .

 

  Network Adapter 1

    DNS Server Search Order - Before:

        192.168.0.1

    Replaced DNS server search order list.

 

--------------------------------------------------------------------------------

 

 

  Network Adapter 1

    DNS Server Search Order - After:

        192.168.0.1

        192.168.0.2

Replacing One DNS Server with Another

If only one DNS server has changed and the others are still valid, you may want to simply replace the IP address of the old server with the IP address of the new server, keeping the address in the same spot in the search order. Such a need might arise when a DNS server that is running on old hardware is replaced by a new computer. After the change is made, the clients of the replaced server must be reconfigured with the IP address of the new server.

Scripting Steps

caution.gif  Caution
This script may make changes in your computer configuration. Run it only on a test computer and note the settings involved before running it.

Listing 31 checks whether the IP address of a given server is on the DNS server search order list (contained in a string array in the DNSServerSearchOrder property) for each network adapter configuration on a computer. If the IP address is found, the script removes it and adds the IP address of the new server in its place with the SetDNSServerSearchOrder method.

  1. Create a variable to specify the computer name.

  2. Assign IP addresses to the variables representing the old DNS server to be replaced and the new server.

  3. Use a GetObject call to connect to the WMI namespace root\cimv2, and set the impersonation level to “impersonate.”

  4. Use the ExecQuery method to query the Win32_NetworkAdapterConfiguration class, filtering the WQL query with “WHERE IPEnabled = True.”

    This returns a collection consisting of all the network adapter configurations on the computer for which IP is enabled.

  5. For each network adapter configuration in the collection, perform the following tasks.

  6. Display the index and current DNS server search order list of the network adapter

  7. Iterate through the list of DNS server IP addresses with a For loop, and if the IP address to be replaced is found, replace it with the new IP address and set a Boolean flag.

  8. If the flag is set to True, call the SetDNSServerSearchOrder method of the Win32_NetworkAdapterConfiguration class, passing it as a parameter the updated array of IP addresses representing the new DNS server search order.

  9. Check the value returned by the method, and display a success or error message.

  10. If the IP address to be replaced is not found, display a message.

  11. Requery Win32_NetworkAdapterConfiguration and display the new DNS server search order.

    Listing 31   Dns-replaceserver.vbs

  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56

On Error Resume Next
 
strComputer = "."
strOldDNSServer = "192.168.0.2"
strNewDNSServer = "192.168.0.5"
 
Set objWMIService = GetObject("winmgmts:" _
 & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colNicConfigs = objWMIService.ExecQuery _
 ("SELECT * FROM Win32_NetworkAdapterConfiguration WHERE IPEnabled = True")
 
WScript.Echo VbCrLf & "Computer: " & strComputer
 
For Each objNicConfig In colNicConfigs
  WScript.Echo VbCrLf & "  Network Adapter " & objNicConfig.Index
  arrDNSServerSearchOrder = objNicConfig.DNSServerSearchOrder
  WScript.Echo "    DNS Server Search Order - Before:"
  If Not IsNull(objNicConfig.DNSServerSearchOrder) Then
    For Each strDNSServer In objNicConfig.DNSServerSearchOrder
      WScript.Echo "        " & strDNSServer
    Next
  End If
  blnFound = 0
  For i = 0 to UBound(arrDNSServerSearchOrder)
    If arrDNSServerSearchOrder(i) = strOldDNSServer Then
      arrDNSServerSearchOrder(i) = strNewDNSServer
      blnFound = 1
    End If
  Next
  If blnFound Then
    retSetDNS = objNicConfig.SetDNSServerSearchOrder(arrDNSServerSearchOrder)
    If retSetDNS = 0 Then
      WScript.Echo "    Replaced " & strOldDNSServer & " with " & _
       strNewDNSServer & " in DNS search order."
    Else
      WScript.Echo "    Unable to change DNS server search order."
    End If
  Else
    WScript.Echo "    DNS server " & strOldDNSServer & " not found."
  End If
Next
 
WScript.Echo VbCrLf & String(80, "-")
 
Set colNicConfigs = objWMIService.ExecQuery _
 ("SELECT * FROM Win32_NetworkAdapterConfiguration WHERE IPEnabled = True")
 
For Each objNicConfig In colNicConfigs
  WScript.Echo VbCrLf & "  Network Adapter " & objNicConfig.Index
  WScript.Echo "    DNS Server Search Order - After:"
  If Not IsNull(objNicConfig.DNSServerSearchOrder) Then
    For Each strDNSServer In objNicConfig.DNSServerSearchOrder
      WScript.Echo "        " & strDNSServer
    Next
  End If
Next

When you use Cscript.exe to run this script, output similar to the following is displayed in the command window:

C:\scripts>dns-replaceserver.vbs

 

Computer: .

 

  Network Adapter 1

    DNS Server Search Order - Before:

        192.168.0.3

        192.168.0.1

        192.168.0.2

        192.168.0.4

    Replaced 192.168.0.2 with 192.168.0.5 in DNS search order.

 

--------------------------------------------------------------------------------

 

 

  Network Adapter 1

    DNS Server Search Order - After:

        192.168.0.3

        192.168.0.1

        192.168.0.5

        192.168.0.4

Adding a DNS Server at the End of the Search Order

Rather than replacing the IP address of an old DNS server with that of a new one in the DNS server search order list, you might want to add the new server to the end of the list. This script shows how to do this.

Scripting Steps

caution.gif  Caution
This script may make changes in your computer configuration. Run it only on a test computer and note the settings involved before running it.

Listing 32 adds a new DNS server at the end of the DNS server search order list for each network adapter configuration on a computer.

  1. Create a variable to specify the computer name.

  2. Assign a new IP addresses to the variable representing the new DNS server.

  3. Use a GetObject call to connect to the WMI namespace root\cimv2, and set the impersonation level to “impersonate.”

  4. Use the ExecQuery method to query the Win32_NetworkAdapterConfiguration class, filtering the WQL query with “WHERE IPEnabled = True.”

    This returns a collection consisting of all the network adapter configurations on the computer for which IP is enabled.

  5. For each network adapter configuration in the collection, perform the following tasks.

  6. Create a variable, intNewArraySize, and set it to zero at the top of the loop to clear values from previous iterations.

  7. Display the index and current DNS server search order list of the network adapter

  8. Assign the array returned by the DNSServerSearchOrder property to the variable arrDNSServerSearchOrder.

  9. Redimension (with the VBScript ReDim statement) arrDNSServerSearchOrder on line 20, incrementing the number of array elements by one to accommodate the new DNS server IP address. Note that in VBScript the number used by the ReDim statement is one less than the resulting array size.

  10. Assign the new DNS server's IP address to the final array element.

  11. Call the SetDNSServerSearchOrder method of Win32_NetworkAdapterConfiguration, passing it the changed array of IP addresses.

  12. Check the value returned by the method, and display a success or error message.

  13. Requery Win32_NetworkAdapterConfiguration and display the new DNS server search order.

    Listing 32   Dns-addserver-end.vbs

  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51

On Error Resume Next
 
strComputer = "."
strNewDNSServer = "192.168.0.4"
 
Set objWMIService = GetObject("winmgmts:" _
 & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colNicConfigs = objWMIService.ExecQuery _
 ("SELECT * FROM Win32_NetworkAdapterConfiguration WHERE IPEnabled = True")
 
WScript.Echo VbCrLf & "Computer: " & strComputer
 
For Each objNicConfig In colNicConfigs
  intNewArraySize = 0
  WScript.Echo VbCrLf & "  Network Adapter " & objNicConfig.Index
  arrDNSServerSearchOrder = objNicConfig.DNSServerSearchOrder
  WScript.Echo "    DNS Server Search Order - Before:"
  If Not IsNull(arrDNSServerSearchOrder) Then
    For Each strDNSServer In arrDNSServerSearchOrder
      WScript.Echo "        " & strDNSServer
    Next
  End If
  WScript.Echo "    Adding " & strNewDNSServer & " to end of " & _
   "DNS search order."
  intNewArraySize = UBound(arrDNSServerSearchOrder) + 1
  ReDim Preserve arrDNSServerSearchOrder(intNewArraySize)
  arrDNSServerSearchOrder(intNewArraySize) = strNewDNSServer
  intSetDNS = _
   objNicConfig.SetDNSServerSearchOrder(arrDNSServerSearchOrder)
  If intSetDNS = 0 Then
    WScript.Echo "    Added " & strNewDNSServer & _
     " to end of DNS search order."
  Else
    WScript.Echo "    Unable to change DNS server search order."
  End If
Next
 
WScript.Echo VbCrLf & String(80, "-")
 
Set colNicConfigs = objWMIService.ExecQuery _
 ("SELECT * FROM Win32_NetworkAdapterConfiguration WHERE IPEnabled = True")
 
For Each objNicConfig In colNicConfigs
  WScript.Echo VbCrLf & "  Network Adapter " & objNicConfig.Index
  WScript.Echo "    DNS Server Search Order - After:"
  If Not IsNull(objNicConfig.DNSServerSearchOrder) Then
    For Each strDNSServer In objNicConfig.DNSServerSearchOrder
      WScript.Echo "        " & strDNSServer
    Next
  End If
Next

When you use Cscript.exe to run this script, output similar to the following is displayed in the command window:

C:\scripts>dns-addserver-end.vbs

 

Computer: .

 

  Network Adapter 1

    DNS Server Search Order - Before:

        192.168.0.1

        192.168.0.2

    Adding 192.168.0.4 to end of DNS search order.

    Added 192.168.0.4 to end of DNS search order.

 

--------------------------------------------------------------------------------

 

 

  Network Adapter 1

    DNS Server Search Order - After:

        192.168.0.1

        192.168.0.2

        192.168.0.4

Adding a DNS Server to the Beginning of the Search Order

Finally, you might want to add a new DNS server to the beginning of the search order list and this script shows how. The main change here is to replace the one line of code that adds a new IP address at the end of the array in Dns-addserver-end.vbs (line 21) with four lines below that move each array element down in the array and add the new IP address at the top (lines 21–24).

Scripting Steps

caution.gif  Caution
This script may make changes in your computer configuration. Run it only on a test computer and note the settings involved before running it.

Listing 33 adds a new DNS server at the beginning of the DNS server search order list for each network adapter configuration on a computer.

  1. Create a variable to specify the computer name.

  2. Assign a new IP addresses to the variable representing the new DNS server.

  3. Use a GetObject call to connect to the WMI namespace root\cimv2, and set the impersonation level to “impersonate.”

  4. Use the ExecQuery method to query the Win32_NetworkAdapterConfiguration class, filtering the WQL query with “WHERE IPEnabled = True.”

    This returns a collection consisting of all the network adapter configurations on the computer for which IP is enabled.

  5. For each network adapter configuration in the collection, perform the following tasks.

  6. Create a variable, intNewArraySize, and set it to zero at the top of the loop to clear values from previous iterations.

  7. Display the index and current DNS server search order list of the network adapter.

  8. Assign the array returned by the DNSServerSearchOrder property to the variable arrDNSServerSearchOrder.

  9. Redimension (with the VBScript ReDim statement) arrDNSServerSearchOrder on line 20, incrementing the number of array elements by one to accommodate the new DNS server IP address. Note that in VBScript the number used by the ReDim statement is one less than the resulting array size.

  10. Loop through all the array elements except the last (the new one which is still empty) and assign each element to the following element in the array. This moves the whole array down one step.

  11. Assign the IP address of the new DNS server to the first array element (which has an index of 0).

  12. Call the SetDNSServerSearchOrder method of Win32_NetworkAdapterConfiguration, passing it the changed array of IP addresses.

  13. Check the value returned by the method, and display a success or error message.

  14. Requery Win32_NetworkAdapterConfiguration and display the new DNS server search order.

    Listing 33   Dns-addserver-top.vbs

  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
30
41
42
43
44
45
46
47
48
49
50
51
52
53

On Error Resume Next
 
strComputer = "."
strNewDNSServer = "192.168.0.3"
 
Set objWMIService = GetObject("winmgmts:" _
 & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colNicConfigs = objWMIService.ExecQuery _
 ("SELECT * FROM Win32_NetworkAdapterConfiguration WHERE IPEnabled = True")
 
WScript.Echo VbCrLf & "Computer: " & strComputer
 
For Each objNicConfig In colNicConfigs
  intNewArraySize = 0
  WScript.Echo VbCrLf & "  Network Adapter " & objNicConfig.Index
  arrDNSServerSearchOrder = objNicConfig.DNSServerSearchOrder
  WScript.Echo "    DNS Server Search Order - Before:"
  If Not IsNull(arrDNSServerSearchOrder) Then
    For Each strDNSServer In arrDNSServerSearchOrder
      WScript.Echo "        " & strDNSServer
    Next
  End If
  WScript.Echo "    Adding " & strNewDNSServer & " to top of " & _
   "DNS search order."
  intNewArraySize = UBound(arrDNSServerSearchOrder) + 1
  ReDim Preserve arrDNSServerSearchOrder(intNewArraySize)
  For i = (intNewArraySize - 1) To 0 Step -1
    arrDNSServerSearchOrder(i + 1) = arrDNSServerSearchOrder(i)
  Next
  arrDNSServerSearchOrder(0) = strNewDNSServer
  intSetDNS = objNicConfig.SetDNSServerSearchOrder(arrDNSServerSearchOrder)
  If intSetDNS = 0 Then
    WScript.Echo "    Added " & strNewDNSServer & _
     " to top of DNS search order."
  Else
    WScript.Echo "    Unable to change DNS server search order."
  End If
Next
 
WScript.Echo VbCrLf & String(80, "-")
 
Set colNicConfigs = objWMIService.ExecQuery _
 ("SELECT * FROM Win32_NetworkAdapterConfiguration WHERE IPEnabled = True")
 
For Each objNicConfig In colNicConfigs
  WScript.Echo VbCrLf & "  Network Adapter " & objNicConfig.Index
  WScript.Echo "    DNS Server Search Order - After:"
  If Not IsNull(objNicConfig.DNSServerSearchOrder) Then
    For Each strDNSServer In objNicConfig.DNSServerSearchOrder
      WScript.Echo "        " & strDNSServer
    Next
  End If
Next

When you use Cscript.exe to run this script, output similar to the following is displayed in the command window:

C:\scripts>dns-addserver-top.vbs

 

Computer: .

 

  Network Adapter 1

    DNS Server Search Order - Before:

        192.168.0.1

        192.168.0.2

        192.168.0.4

    Adding 192.168.0.3 to top of DNS search order.

    Added 192.168.0.3 to top of DNS search order.

 

--------------------------------------------------------------------------------

 

 

  Network Adapter 1

    DNS Server Search Order - After:

        192.168.0.3

        192.168.0.1

        192.168.0.2

        192.168.0.4

Changing the DNS Domain

Sometimes you might need to change the DNS domain on multiple clients — for example, when you add a child domain or you merge two domains. If many or widely dispersed clients are involved, scripting can be a time-saving and error-reducing alternative to manual configuration.

In Windows 2000, Windows XP, and Windows Server 2003, you can use the SetDNSDomain() method of the Win32_NetworkAdapterConfiguration class to set the DNS domain for a specific network adapter. You must pass this method a single parameter, a string indicating the name of the new DNS domain. In Windows NT Server 4.0, the Win32_NetworkAdapterConfiguration setting applies globally to all network adapters.

In Windows XP and Windows Server 2003, the Win32_ComputerSystem methods JoinDomainOrWorkgroup() and UnjoinDomainOrWorkgroup() enable you to join or unjoin a computer to or from an Active Directory domain. With these methods, the changes apply to all network adapters. To make the same changes by using the Windows XP GUI, you can use the Network Identification Wizard.

Win32_ComputerSystem also includes Domain and DomainRole properties that return Active Directory domain membership and the role the computer plays in it — for example, member workstation or domain controller. You may have to coordinate changes in DNS domains with corresponding changes in Active Directory.

Changing the DNS Domain with Win32_NetworkAdapterConfiguration

The following script demonstrates how to use the SetDNSDomain() method of the Win32_NetworkAdapterConfiguration class to set the DNS domain for all network adapters. Because this method works on a per-adapter basis, you could also use it to set the DNS domain on a specific network adapter.

Scripting Steps

caution.gif  Caution
This script may make changes in your computer configuration. Run it only on a test computer and note the settings involved before running it.

  1. Create a variable to specify the computer name.

  2. Create a variable to specify the new DNS domain name.

  3. Use a GetObject call to connect to the WMI namespace root\cimv2, and set the impersonation level to “impersonate.”

  4. Use the ExecQuery method to query the Win32_NetworkAdapterConfiguration class.

    This returns a collection consisting of all the network adapter configurations on the computer.

  5. For each network adapter configuration in the collection, perform the following tasks.

  6. Display the index, description DNS host name and current DNS domain of the network adapter

  7. Call the SetDNSDomain method of Win32_NetworkAdapterConfiguration, passing it the variable containing the new DNS domain name.

  8. Check the value returned by the method, and display a success or error message.

  9. Requery Win32_NetworkAdapterConfiguration and display the new DNS domain.

    Listing 34   Dns-setdomain.vbs

  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47

On Error Resume Next
 
strComputer = "."
strDNSDomain = "fabrikam.com"
 
Set objWMIService = GetObject("winmgmts:" _
 & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colNicConfigs = objWMIService.ExecQuery _
 ("SELECT * FROM Win32_NetworkAdapterConfiguration WHERE IPEnabled = True")
 
For Each objNicConfig In colNicConfigs
  strDNSHostName = objNicConfig.DNSHostName
Next
WScript.Echo VbCrLf & "DNS Host Name: " & strDNSHostName
 
For Each objNicConfig In colNicConfigs
  WScript.Echo VbCrLf & _
   "  Network Adapter " & objNicConfig.Index & VbCrLf & _
   "    " & objNicConfig.Description & VbCrLf & _
   "    DNS Domain - Before: " & objNicConfig.DNSDomain
  intSetDomain = objNicConfig.SetDNSDomain(strDNSDomain)
  If intSetDomain = 0 Then
    WScript.Echo "    Successfully set DNS domain to " & strDNSDomain
  ElseIf intSetDomain = 1 Then
    WScript.Echo "    Successfully set DNS domain to " & strDNSDomain & _
     VbCrLf & "    Must reboot."
  Else
    WScript.Echo "    Unable to set DNS domain."
  End If
Next
 
WScript.Echo VbCrLf & String(80, "-")
 
Set colNicConfigs = objWMIService.ExecQuery _
 ("SELECT * FROM Win32_NetworkAdapterConfiguration WHERE IPEnabled = True")
 
For Each objNicConfig In colNicConfigs
  strDNSHostName = objNicConfig.DNSHostName
Next
WScript.Echo VbCrLf & "DNS Host Name: " & strDNSHostName
 
For Each objNicConfig In colNicConfigs
  WScript.Echo VbCrLf & _
   "  Network Adapter " & objNicConfig.Index & VbCrLf & _
   "    " & objNicConfig.Description & VbCrLf & _
   "    DNS Domain - After: " & objNicConfig.DNSDomain
Next

When you use Cscript.exe to run this script, output similar to the following is displayed in the command window:

C:\scripts>dns-setdomain.vbs

 

DNS Host Name: client1

 

  Network Adapter 1

    3Com 3C920 Integrated Fast Ethernet Controller (3C905C-TX Compatible) - Pack

et Scheduler Miniport

    DNS Domain - Before:

    Successfully set DNS domain to fabrikam.com

 

--------------------------------------------------------------------------------

 

 

DNS Host Name: client1

 

  Network Adapter 1

    3Com 3C920 Integrated Fast Ethernet Controller (3C905C-TX Compatible) - Pack

et Scheduler Miniport

    DNS Domain - After: fabrikam.com

Changing the Domain with Win32_ComputerSystem

The following script demonstrates how to use the JoinDomainOrWorkgroup() method of the Win32_ComputerSystem class to join a computer to an Active Directory domain. The changes apply to all network adapters, in contrast to the SetDNSDomain() method of the Win32_NetworkAdapterConfiguration class, which applies changes only to each specified adapter. Win32_ComputerSystem also provides an UnjoinDomainOrWorkgroup() method. Both the JoinDomainOrWorkgroup() and UnjoinDomainOrWorkgroup() methods are available only on Windows XP and Windows Server 2003.

You may have to coordinate domain changes with corresponding changes in Active Directory.

Table 15 describes the five parameters that the JoinDomainOrWorkgroup() method accepts.

Table 15   JoinDomainOrWorkgroup() Parameters

Parameter

Description

Name

The name of the domain or workgroup to join. Cannot be NULL.

Password

Must be specified if an alternative Username parameter is passed. Can be NULL if no Username is passed.

Username

NetBIOS name and user account, in the form DOMAIN\user. If this parameter is NULL, the credentials under which the script is run are used.

AccountOU

Optional. Can be NULL. The fully distinguished name of the Active Directory organizational unit, for example: OU=HR, DC=fabrikam, DC=com.

FJoinOptions

A set of bit flags that specify options for joining a domain or workgroup. If you do not set this parameter, the default of 1 (Join Domain) is used and the name specified in the first parameter is assumed to be a workgroup. You can set 0 or more of these parameters simultaneously by OR-ing the requisite values together, as the following script illustrates.

Table 16 describes valid values for the FjoinOptions parameter of JoinDomainOrWorkgroup() method.

Table 16   FJoinOptions Values

Value:Decimal& Hex

Value

Meaning

1

&h00001

Join Domain

Default. Joins a computer to a domain. If this value is not specified, the join is a computer to a workgroup.

2

&h00002

Acct Create

Creates an account on a domain.

4

&h00004

Acct Delete

Deletes an account when a domain exists.

16

&h00010

Win9X Upgrade

The join operation is part of an upgrade from Windows 95 or Windows 98 to Windows NT 4.0 or Windows 2000.

32

&h00020

Domain Join If Joined

Allows a join to a new domain even if the computer is already joined to a domain.

64

&h00040

Join Unsecure

Performs an unsecured join.

128

&h00080

Machine Password Passed

The computer, not the user, password is passed. This option is only valid for unsecure joins.

256

&h00100

Deferred SPN Set

Writing SPN and DnsHostName attributes on the computer object should be deferred until the rename that follows the join.

262144

&h40000

Install Invocation

The APIs were invoked during install.

In addition, Win32_ComputerSystem contains an UnjoinDomainOrWorkgroup() method (also new for Windows XP), which removes a computer from a domain.

Scripting Steps

caution.gif  Caution
This script may make changes in your computer configuration. Run it only on a test computer and note the settings involved before running it.

Listing 35 changes the domain globally for the computer system.

  1. Define a constant, JOIN_DOMAIN, and set it equal to 1.

    note.gif  Note
    Note that this value joins a computer to a domain only if it does not already belong to one. To join a computer that already is joined to a domain to a new domain, create a constant, DOMAIN_JOIN_IF_JOINED, and set it equal to 32. Then in the call to the JoinDomainOrWorkgroup method, pass DOMAIN_JOIN_IF_JOINED as the final parameter rather than JOIN_DOMAIN.

  2. Create a variable to specify the computer name.

  3. Create a variable to specify the new DNS domain name.

  4. Use a GetObject call to connect to the WMI namespace root\cimv2, and set the impersonation level to “impersonate.”

  5. Use the ExecQuery method to query the Win32_ComputerSystem class.

  6. This returns a collection consisting of all computer systems on the computer. Only one computer system is returned.

  7. For each network adapter configuration in the collection, perform the following tasks.

  8. Display the computer name and current domain.

  9. Call the JoinDomainOrWorkgroup method of Win32_ComputerSystem, passing it two parameters: the variable representing the new domain name and the constant representing the value 1, which indicates the Join Domain option. Mark the places of blank optional parameters with commas.

  10. Check the value returned by the method, and display a success or error message.

  11. Requery Win32_ComputerSystem and display the changed domain.

  12. Use a Select Case statement to convert the integer value returned by the DomainRole property into a descriptive string and display it.

    Listing 35   Dns-setdomain-global.vbs

  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48

On Error Resume Next
 
Const JOIN_DOMAIN = 1
strComputer = "."
strDomainName = "fabrikam.com"
 
Set objWMIService = GetObject("winmgmts:" _
 & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colCompSystems = objWMIService.ExecQuery _
 ("SELECT * FROM Win32_ComputerSystem")
 
For Each objCompSystem In colCompSystems
  WScript.Echo VbCrLf & "Computer Name: " & LCase(objCompSystem.Name)
  WScript.Echo "  Domain - Before: " & LCase(objCompSystem.Domain)
  intJoinDomain = objCompSystem.JoinDomainOrWorkgroup(strDomainName,,,, _
   JOIN_DOMAIN)
  If intJoinDomain = 0 Then
    WScript.Echo "    Joined computer to " & strDomainName & " domain."
  ElseIf intJoinDomain = 1 Then
    WScript.Echo "    Joined computer to " & strDomainName & " domain." & _
     VbCrLf & "    Must reboot."
  Else
    WScript.Echo "    Unable to join computer to " & strDomainName & _
     " domain."
WScript.Echo "Return value of JoinDomainOrWorkgroup method: " & intJoinDomain
  End If
Next
 
WScript.Echo VbCrLf & String(80, "-")
 
Set colCompSystems = objWMIService.ExecQuery _
 ("SELECT * FROM Win32_ComputerSystem")
 
For Each objCompSystem In colCompSystems
  WScript.Echo VbCrLf & "Computer Name: " & LCase(objCompSystem.Name)
  WScript.Echo "  Domain - After: " & LCase(objCompSystem.Domain)
  intDomainRole = objCompSystem.DomainRole
  Select Case intDomainRole
    Case 0 strDomainRole = "Standalone Workstation"
    Case 1 strDomainRole = "Member Workstation"
    Case 2 strDomainRole = "Standalone Server"
    Case 3 strDomainRole = "Member Server"
    Case 4 strDomainRole = "Backup Domain Controller"
    Case 5 strDomainRole = "Primary Domain Controller"
    Case Else strDomainRole = "Cannot determine domain role."
  End Select
  WScript.Echo "  Domain Role: " & strDomainRole
Next

When you use Cscript.exe to run this script, output similar to the following is displayed in the command window:

C:\scripts>dns-setdomain-global.vbs

 

Computer Name: client1

  Domain - Before:

    Joined computer to fabrikam.com domain.

 

--------------------------------------------------------------------------------

 

Computer Name: client1

  Domain - After: fabrikam.com

  Domain Role: Member Workstation

Changing the DNS Domain Suffix Search Order

Besides changing a computer’s DNS domain, you can also set the search order for the DNS domain suffix. This may be necessary when the host must try to resolve unqualified names on DNS servers in more than one domain. Such a situation might occur when a network includes multiple secondary DNS servers in different domains, or when a multihomed computer has each network adapter joined to a different domain.

The following script sets the DNS domain suffixes that correspond to the names you would enter in the text box under Append these DNS suffixes (in order) on the DNS tab of the Advanced TCP/IP Settings dialog box.

caution.gif  Caution
This script may make changes in your computer configuration. Run it only on a test computer and note the settings involved before running it.

SetDNSSuffixSearchOrder is a static method, which means that it applies to all instances of the Win32_NetworkAdapterConfiguration class (that is, to all IP-enabled network adapters). This means that you can use the simpler Get() method of the SWbemServices object (returned by the previous GetObject call to the winmgmts: moniker) to get an object representing the whole class, rather than using the more complex ExecQuery() method with a WQL query to get a collection of objects representing instances of the class. The Get() method appears on line 19:

Set objNetworkSettings = objWMIService.Get("Win32_NetworkAdapterConfiguration")

Instead of simply calling the SetDNSSuffixSearchOrder method without parameters, as you do with EnableDHCP, you must pass it an array of strings containing the suffix names.

If you needed only to call the SetDNSSuffixSearchOrder method in a script, you could use more compact ways of binding to the Win32_NetworkAdapterConfiguration class. Here are two examples:

Set objNicConfig = GetObject("winmgmts:\\" & strComputer &_
 "\root\cimv2:Win32_NetworkAdapterConfiguration")



Set objNicConfig = GetObject("winmgmts:").Get _
 ("Win32_NetworkAdapterConfiguration")

Which way is best in a specific context is often determined by coding style or organizational standards.

Scripting Steps

Listing 36 replaces the old DNS domain suffix search order list with a new list for all network adapters.

  1. Create a variable to specify the computer name.

  2. Create an array variable to specify the list of DNS domain suffixes.

  3. Use a GetObject call to connect to the WMI namespace root\cimv2, and set the impersonation level to “impersonate.”

  4. Use the ExecQuery method to query the Win32_NetworkAdapterConfiguration class, filtering the WQL query with “WHERE IPEnabled = True.”

    This returns a collection consisting of all the network adapter configurations on the computer for which IP is enabled.

  5. For each network adapter configuration in the collection, perform the following tasks.

  6. Check that the DNSDomainSuffixSearchOrder property is not Null

  7. Iterate through the array of strings returned by the DNSDomainSuffixSearchOrder property,

  8. Concatenate the array elements into a single string.

  9. Display the string containing the list of DNS domain suffixes in order.

  10. Call the SetDNSSuffixSearchOrder method of Win32_NetworkAdapterConfiguration, passing it one parameter: the array containing the list of DNS domain suffixes.

  11. Check the value returned by the method, and display a success or error message.

  12. Requery Win32_NetworkAdapterConfiguration and display the changed list of DNS domain suffixes.

    Listing 36   Dns-replacesuffixlist.vbs

  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58

On Error Resume Next
 
strComputer = "."
arrNewDNSSuffixSearchOrder = Array("hr.fabrikam.com", "contoso.com")
 
Set objWMIService = GetObject("winmgmts:" _
 & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colNicConfigs = objWMIService.ExecQuery _
 ("SELECT * FROM Win32_NetworkAdapterConfiguration WHERE IPEnabled = True")
 
For Each objNicConfig In colNicConfigs
  strDNSHostName = objNicConfig.DNSHostName
Next
WScript.Echo VbCrLf & "DNS Host Name: " & strDNSHostName
 
For Each objNicConfig In colNicConfigs
  WScript.Echo VbCrLf & _
   "  Network Adapter " & objNicConfig.Index & VbCrLf & _
   "    " & objNicConfig.Description & VbCrLf & _
   "    DNS Domain Suffix Search Order - Before:"
  If Not IsNull(objNicConfig.DNSDomainSuffixSearchOrder) Then
    For Each strDNSSuffix In objNicConfig.DNSDomainSuffixSearchOrder
      WScript.Echo "      " & strDNSSuffix
    Next
  End If
Next
 
WScript.Echo VbCrLf & String(80, "-")
 
Set objNetworkSettings = _
 objWMIService.Get("Win32_NetworkAdapterConfiguration")
intSetSuffixes = _
 objNetworkSettings.SetDNSSuffixSearchOrder(arrNewDNSSuffixSearchOrder)
If intSetSuffixes = 0 Then
  WScript.Echo VbCrLf & "Replaced DNS domain suffix search order list."
ElseIf intSetSuffixes = 1 Then
  WScript.Echo VbCrLf & "Replaced DNS domain suffix search order list." & _
   VbCrLf & "    Must reboot."
Else
  WScript.Echo VbCrLf & "Unable to replace DNS domain suffix " & _
   "search order list."
End If
 
WScript.Echo VbCrLf & String(80, "-")
 
Set colNicConfigs = objWMIService.ExecQuery _
 ("SELECT * FROM Win32_NetworkAdapterConfiguration WHERE IPEnabled = True")
For Each objNicConfig In colNicConfigs
  WScript.Echo VbCrLf & _
   "  Network Adapter " & objNicConfig.Index & VbCrLf & _
   "    " & objNicConfig.Description & VbCrLf & _
   "    DNS Domain Suffix Search Order - After:"
  If Not IsNull(objNicConfig.DNSDomainSuffixSearchOrder) Then
    For Each strDNSSuffix In objNicConfig.DNSDomainSuffixSearchOrder
      WScript.Echo "      " & strDNSSuffix
    Next
  End If
Next

When you use Cscript.exe to run this script, output similar to the following is displayed in the command window:

C:\scripts>dns-replacesuffixlist.vbs

 

DNS Host Name: client1

 

  Network Adapter 1

    3Com 3C920 Integrated Fast Ethernet Controller (3C905C-TX Compatible) - Pack

et Scheduler Miniport

    DNS Domain Suffix Search Order - Before:

 

--------------------------------------------------------------------------------

 

Replaced DNS domain suffix search order list.

 

--------------------------------------------------------------------------------

 

  Network Adapter 1

    3Com 3C920 Integrated Fast Ethernet Controller (3C905C-TX Compatible) - Pack

et Scheduler Miniport

    DNS Domain Suffix Search Order - After:

      hr.fabrikam.com

      contoso.com

Changing Dynamic DNS Registration Settings

As IP addresses change for DHCP clients, DNS registration and dynamic update automate the process of keeping host name and IP address mappings change current on your DNS servers. Although previously this update process had to be manually performed by administrators, DNS dynamic update (RFC 2136) allows clients and DHCP servers to keep address (A) and pointer record (PTR) resource records up-to-date on the DNS server without manual intervention.

As usual, the Win32_NetworkAdapterConfiguration class provides read-only properties to expose these DNS registration and update settings and a method to change them. The parameters you must pass to the SetDynamicDNSRegistration method, as well as the two Boolean properties they set, map to two check boxes at the bottom of the DNS tab of the Advanced TCP/IP Settings dialog box. “Register this connection’s addresses in DNS” in the Windows interface is equivalent to the FullDNSRegistrationEnabled property; “Use this connection’s DNS suffix in DNS registration” is equivalent to the DomainDNSRegistrationEnabled property. Both properties and the method are new for Windows XP and Windows Server 2003. The value of DomainDNSRegistrationEnabled, the default of which is False, is used only if FullDNSRegistrationEnabled is True; otherwise it is ignored.

You can look in the Windows interface to find the name to which the FullDNSRegistrationEnabled property refers. Open Control Panel, click System, click the Computer Name tab, and then view the Full computer name field. The value in this field consists of the host name with the domain name appended. If FullDNSRegistrationEnabled is True, the IP addresses for the network adapter are registered in DNS by using this name.

If the DomainDNSRegistrationEnabled property is True, the IP addresses are additionally registered in DNS by using the DNSDomain property for the specific network adapter.

For example, on a multihomed computer whose network adapters are each connected to a different network with a different domain structure, you might need to use connection-specific DNS suffixes in domain registration. In such cases, the client might want to register a different domain suffix for each network connection. Setting FullDNSRegistrationEnabled and DomainDNSRegistrationEnabled both to True would enable this.

Scripting Steps

caution.gif  Caution
This script may make changes in your computer configuration. Run it only on a test computer and note the settings involved before running it.

This script changes settings for how dynamic DNS registration is accomplished by using the SetDynamicDNSRegistration() method of the Win32_NetworkAdapterConfiguration class to modify the DomainDNSRegistrationEnabled and FullDNSRegistrationEnabled properties.

The method and properties are new for Windows XP and Windows Server 2003. The script does not check for the operating system version; however, if the SetDynamicDNSRegistration does not return a 0, indicating success, the script traps the error and displays a message.

  1. Create a variable to specify the computer name.

  2. Create two Boolean variables to specify the desired settings for the DomainDNSRegistrationEnabled and FullDNSRegistrationEnabled properties.

  3. Use a GetObject call to connect to the WMI namespace root\cimv2, and set the impersonation level to “impersonate.”

  4. Use the ExecQuery method to query the Win32_NetworkAdapterConfiguration class, filtering the WQL query with “WHERE IPEnabled = True.”

    This returns a collection that consists of all the network adapter configurations on the computer for which IP is enabled.

  5. For each network adapter configuration in the collection, perform the following tasks.

  6. Display the current DNS dynamic registration settings.

  7. Call the SetDynamicDNSRegistration method of Win32_NetworkAdapterConfiguration, passing it the two Boolean parameters set at the beginning of the script.

  8. Check the value returned by the method, and display a success or error message.

  9. Requery Win32_NetworkAdapterConfiguration and display the changed DNS dynamic registration settings.

    Listing 37   Dns-setdynreg.vbs

  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50

On Error Resume Next
 
strComputer = "."
blnFullDNSRegistrationEnabled = True
blnDomainDNSRegistrationEnabled = True
 
Set objWMIService = GetObject("winmgmts:" _
 & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colNicConfigs = objWMIService.ExecQuery _
 ("SELECT * FROM Win32_NetworkAdapterConfiguration WHERE IPEnabled = True")
 
For Each objNicConfig In colNicConfigs
  strDNSHostName = objNicConfig.DNSHostName
Next
WScript.Echo VbCrLf & "DNS Host Name: " & strDNSHostName
 
For Each objNicConfig In colNicConfigs
  WScript.Echo VbCrLf & _
   "  Network Adapter " & objNicConfig.Index & VbCrLf & _
   "    " & objNicConfig.Description & VbCrLf & _
   "    DNS Full Registration Enabled - Before: " & _
   objNicConfig.FullDNSRegistrationEnabled & VbCrLf & _
   "    DNS Domain Registration Enabled - Before: " & _
   objNicConfig.DomainDNSRegistrationEnabled
  intDynReg = objNicConfig.SetDynamicDNSRegistration _
   (blnFullDNSRegistrationEnabled, blnDomainDNSRegistrationEnabled)
  If intDynReg = 0 Then
    WScript.Echo VbCrLf & "    Successfully set dynamic DNS registration."
  ElseIf intDynReg = 1 Then
    WScript.Echo VbCrLf & _
     "    Successfully set dynamic DNS registration." & _
     VbCrLf & "    Must reboot."
  Else
    WScript.Echo VbCrLf & "    Unable to set dynamic DNS registration."
  End If
Next
 
WScript.Echo VbCrLf & String(80, "-")
 
Set colNicConfigs = objWMIService.ExecQuery _
 ("SELECT * FROM Win32_NetworkAdapterConfiguration WHERE IPEnabled = True")
 
For Each objNicConfig In colNicConfigs
  WScript.Echo VbCrLf & "  Network Adapter " & objNicConfig.Index & _
 VbCrLf &   "    " & objNicConfig.Description & VbCrLf & _
   "    DNS Full Registration Enabled - After: " & _
   objNicConfig.FullDNSRegistrationEnabled & VbCrLf & _
   "    DNS Domain Registration Enabled - After: " & _
   objNicConfig.DomainDNSRegistrationEnabled
Next

When you use Cscript.exe to run this script, output similar to the following is displayed in the command window:

C:\scripts>dns-setdynreg.vbs

 

DNS Host Name: client1

 

  Network Adapter 1

    3Com 3C920 Integrated Fast Ethernet Controller (3C905C-TX Compatible) - Pack

et Scheduler Miniport

    DNS Full Registration Enabled - Before:

    DNS Domain Registration Enabled - Before:

 

    Successfully set dynamic DNS registration.

 

--------------------------------------------------------------------------------

 

  Network Adapter 1

    3Com 3C920 Integrated Fast Ethernet Controller (3C905C-TX Compatible) - Pack

et Scheduler Miniport

    DNS Full Registration Enabled - After: True

    DNS Domain Registration Enabled - After: True

Scenario: Changing DNS Servers and Domains

In times of major business changes, such as mergers, acquisitions, and reorganizations, the DNS domain hierarchy of an organization may change and hosts may have to be reconfigured to function within the new structure.

In this scenario, the IT department at Fabrikam, Inc. is assigning clients that were formerly in the top-level fabrikam.com domain to different subdomains: hr.fabrikam.com, it.fabrikam.com and ac.fabrikam.com. Each new subdomain requires a new DNS server search order for the clients on it. The primary DNS server for each subdomain will also be a backup for the other two subdomains.

This script uses the Win32_NetworkAdapterConfiguration methods SetDNSDomain() and SetDNSServerSearchOrder(), rather than EnableDNS(). The latter requires two other optional parameters, which could be left blank; the first two methods set precisely the parameters required by this example. If necessary, you could easily expand the script to also configure the hosts’ dynamic registration settings with the SetDynamicDNSRegistration() method.

Keep in mind that in an operation like this one, configuring the client is only part of the task: you must also make corresponding changes on the DNS servers. Scripting DNS servers is beyond the scope of this paper.

Scripting Steps

caution.gif  Caution
This script may make changes in your computer configuration. Run it only on a test computer and note the settings involved before running it.

Listing 38 takes a text file as input. You must create this file before running the script. The path to the file is specified in a variable; in this example, it is C:\Scripts\Hosts.txt. Each line of the text file contains a host name and a new domain name, separated by a comma (with no spaces in between). The final line must NOT be terminated with an Enter character, because the following line would be read by the script as an empty entry.

client1,hr
client2,it
server1,ac

For each host, the script assigns the new domain name and a new DNS server search order. The new order depends on the new domain name: each subdomain has its own primary DNS server, which serves as a backup for the other two subdomains.

The script creates a comma-separated values (.csv) text file and logs the results of these operations to it. The path to the file is specified in a variable; in this case, it is C:\Scripts\Newhosts.csv.

  1. Define constants for FileSystemObject.

  2. Create variables specifying the paths to the input and output files.

  3. Create variables specifying the name of the top-level domain.

  4. Create three arrays of strings containing the DNS server search orders for each sub-domain.

  5. Create a FileSystemObject and use it to open the file and read the contents into a string.

  6. Call the GetInput function, passing it the name of the input text file. The function reads the contents of the input file and returns them as a string.

  7. Use the VBScript Split function, with the VbCrLf constant as the delimiter, to break down the string from the input file into an array with each element consisting of a line of the text file, which should contain the name of a computer and a sub-domain.

  8. Check to see if the specified output file exists. If so, open it for appending. If not, create it and open it for writing.

  9. Iterate through each array element returned by splitting the lines of the input file.

  10. Again using Split, divide each element of the array at the comma, reading the host name into one variable and the sub-domain name into another.

  11. Concatenate the sub-domain name with the top-level domain name to obtain the full domain name.

  12. Display the host name.

  13. Call the PingClient function, passing it the host name.

  14. If the ping receives a reply, connect to the WMI service and trap for an error.

  15. If no error occurs in connecting to WMI, query the WMI service for the collection of all IP-enabled network adapters.

  16. Call the GetSettings subroutine to display current DNS settings and write them to the output file.

  17. Call the ChangeDNS function, which makes the changes in domain and DNS search order specified in the input file and logs the results to the output file.

  18. Again call the GetSettings subroutine to display the changed DNS settings and write them to the output file.

  19. If an error occurred connecting to WMI, display error information.

  20. If the ping does not receive a reply, display an error message.

  21. The GetInput function takes a string with the name of the input text file as a parameter. The function returns a string containing the text from the input file. If the file is empty or cannot be found, the function displays an error message and terminates the script.

  22. The PingClient function takes a string with the name of a host computer as a parameter. The function returns True if the ping receives a reply and False if not.

  23. The GetSettings subroutine displays for each network adapter the index number, description, DNS domain, DNS server search order, IP addresses, and subnet masks.

  24. The ChangeDNS subroutine selects a DNS server search order based on the sub-domain specified for the host in the input file. If the sub-domain is one of the ones included in the logic of the Select Case statement, the subroutine attempts to call the SetDNSDomain method with the name of the new domain. If this method is successful, the subroutine then attempts to call the SetDNSServerSearchOrder method with the selected DNS server search order. The subroutine logs the results and any errors to the output file.

    Listing 38   Dns-move.vbs

  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237

On Error Resume Next
 
' Constants for FileSystemObject
Const FOR_READING = 1
Const FOR_WRITING = 2
Const FOR_APPENDING = 8
 
' Paths to input and output files. Input file must be text file with name
' of accessible machine, comma, and valid domain name on each line.
strFileInput = "c:\scripts\hosts.txt"
strFileOutput = "c:\scripts\newhosts.csv"
 
' Domain name and DNS servers corresponding to subdomains
strTopDomain = "fabrikam.com"
arrDNSSrv1 = Array("192.168.0.1", "192.168.0.2", "192.168.0.3") 'hr
arrDNSSrv2 = Array("192.168.0.2", "192.168.0.3", "192.168.0.1") 'it
arrDNSSrv3 = Array("192.168.0.3", "192.168.0.1", "192.168.0.2") 'ac
 
' Create a Script Runtime FileSystemObject.
Set objFSO = CreateObject("Scripting.FileSystemObject")
 
' If the input file exists, dump contents of input file into a string.
strInput = GetInput(strFileInput)
 
' Get computer info by breaking input stream into array at line breaks.
arrHosts = Split(strInput, VbCrLf)
 
' Check to see if the output file exists. If so, open it for appending.
' If not, create it and open it for writing.
 
If objFSO.FileExists(strFileOutput) Then
  Set objOutputFile = objFSO.OpenTextFile (strFileOutput, FOR_APPENDING)
Else
  Set objOutputFile = objFSO.CreateTextFile(strFileOutput)
End If
If Err <> 0 Then
  Wscript.Echo "Unable to open " & strFileOutput & " for output."
  WScript.Quit
End If
 
' Write header for file.
objOutputFile.WriteLine "Inventory of computers moved to new domains." & _
 VbCrLf  & "Taken " & Now & VbCrLf & VbCrLf & String(120, "-") & VbCrLf
 
For Each strHost In arrHosts
 
' Get names and domains by breaking each computer info array at commas.
  arrComputers = Split(strHost, ",")
  strComputer = arrComputers(0)
  strSubDomain = arrComputers(1)
  strDomain = strSubDomain & "." & strTopDomain
  WScript.Echo VbCrLf & "Host: " & strComputer & VbCrLf
 
' Ping remote computer. If no response display error message and end script
  blnPingSuccess = PingClient(strComputer)
  If blnPingSuccess = True Then
 
' Connect to the WMI service.
    Set objWMIService = GetObject("winmgmts:" _
     & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
 
    If Err = 0 Then
 
' Write header for each computer.
      objOutputFile.WriteLine "Host:,," & strComputer & VbCrLf & VbCrLf & _
       ", Settings before operations:" & VbCrLf
 
' Get current settings and write to output file.
      GetSettings
      objOutputFile.WriteLine VbCrLf & "," & String(60, "-")
 
' Change domain and DNS search order.
      ChangeDNS
 
' Get settings after changes and write to output file.
      objOutputFile.WriteLine VbCrLf & "," & String(60, "-") & VbCrLf & _
       VbCrLf & ",Settings after operations:" & VbCrLf
      GetSettings
      objOutputFile.WriteLine VbCrLf & String(120, "-") & VbCrLf
 
    Else
 
      objOutputFile.WriteLine "Host: " & strComputer & VbCrLf _
       & VbCrLf & "Error connecting to WMI service." & VbCrLf & _
       "Error Number: " & Err.Number & VbCrLf & _
       "Error Source: " & Err.Source & VbCrLf & _
       "Error Description: " & Err.Description & VbCrLf & VbCrLf & _
       String(120, "-") & VbCrLf
      Err.Clear
 
    End If
 
  Else
 
    objOutputFile.WriteLine "Host: " & strComputer & VbCrLf _
     & VbCrLf & ",Unable to connect." & VbCrLf & VbCrLf & _
     String(120, "-") & VbCrLf
 
  End If
 
Next
 
' Write footer for file and close.
objOutputFile.WriteLine String(64, "=") & VbCrLf
objOutputFile.Close
 
WScript.Echo "Inventory complete. Data written to " & strFileOutput & "."
 
'************************************************************************
 
Function GetInput(strFileInput)
 
' Check to see if the input file exists.
' If so, dump contents of input file into a string.
 
If objFSO.FileExists(strFileInput) Then
  Set objInputFile = objFSO.GetFile(strFileInput)
  If objInputFile.Size > 0 Then
    Set objInputFile = objFSO.OpenTextFile(strFileInput, FOR_READING)
    strInputStream = objInputFile.ReadAll
    objInputFile.Close
    GetInput = strInputStream
  Else
    Wscript.Echo strFileInput & " is empty."
    WScript.Quit
  End If
Else
  WScript.Echo strFileInput & " does not exist on this computer."
  WScript.Quit
End If
 
End Function
 
'************************************************************************
 
Function PingClient(strComputer)
 
Set objShell = CreateObject("WScript.Shell")
Set objExec = objShell.Exec("ping -n 2 -w 1000 " & strComputer)
strPingResults = LCase(objExec.StdOut.ReadAll)
If InStr(strPingResults, "reply from") Then
  PingClient = True
Else
  PingClient = False
End If
 
End Function
 
'************************************************************************
 
Sub GetSettings
 
Set colCompSystems = objWMIService.ExecQuery _
("SELECT * FROM Win32_ComputerSystem")
 
For Each objCompSystem in colCompSystems
  objOutputFile.WriteLine VbCrLf & ",Domain:,," & objCompSystem.Domain
Next
 
Set colNicConfigs = objWMIService.ExecQuery("SELECT " & _
 "* FROM Win32_NetworkAdapterConfiguration WHERE IPEnabled=True")
 
For Each objNicConfig In colNicConfigs
  objOutputFile.WriteLine VbCrLf & ",Network Adapter " & _
   objNicConfig.Index & VbCrLf & _
   ",," & objNicConfig.Description & VbCrLf & _
   ",,DNS Domain:,," & objNicConfig.DNSDomain
  strRow = ",,DNS Server Search Order:,,"
  If Not IsNull(objNicConfig.DNSServerSearchOrder) Then
    For Each strDNSServer In objNicConfig.DNSServerSearchOrder
      strRow = strRow & strDNSServer & ",,"
    Next
  End If
  objOutputFile.WriteLine strRow
  strRow = ",,IP Addresses:,,"
  If Not IsNull(objNicConfig.IPAddress) Then
    For Each strIPAddress In objNicConfig.IPAddress
      strRow = strRow & strIPAddress & ",,"
    Next
  End If
  objOutputFile.WriteLine strRow
  strRow = ",,Subnet Masks:,,"
  If Not IsNull(objNicConfig.IPSubnet) Then
    For Each strIPSubnet In objNicConfig.IPSubnet
      strRow = strRow & strIPSubnet & ",,"
    Next
  End If
  objOutputFile.WriteLine strRow
Next
 
End Sub
 
'************************************************************************
 
Sub ChangeDNS
 
Set colNicConfigs = objWMIService.ExecQuery("SELECT " & _
 "* FROM Win32_NetworkAdapterConfiguration WHERE IPEnabled=True")
 
' Test that child domain from input file is valid.
errSubDomain = False
Select Case strSubDomain
  Case "hr" arrDNSServers = arrDNSSrv1
  Case "it" arrDNSServers = arrDNSSrv2
  Case "ac" arrDNSServers = arrDNSSrv3
  Case Else errSubDomain = True
End Select
 
If errSubDomain = False Then
  For Each objNicConfig In colNicConfigs
    objOutputFile.WriteLine VbCrLf & ",Network Adapter " & _
     objNicConfig.Index & VbCrLf & _
     ",," & objNicConfig.Description & VbCrLf & VbCrLf & _
     ",,Attempting to make changes in DNS configuration ..."
    intDomain = objNicConfig.SetDNSDomain(strDomain)
    If intDomain = 0 Then
      objOutputFile.WriteLine ",,Assigned new domain."
      intServers = objNicConfig.SetDNSServerSearchOrder _
       (arrDNSServers)
      If intServers = 0 Then
        objOutputFile.WriteLine ",,Assigned new DNS server " & _
         "search order."
      Else
        objOutputFile.WriteLine ",,Unable to assign new DNS " & _
         "server search order."
      End If
    Else
      objOutputFile.WriteLine ",,Unable to assign new domain or " & _
       "DNS server search order."
    End If
  Next
Else
  objOutputFile.WriteLine "Subdomain" & strSubDomain & _
  "could not be found."
End If
 
End Sub

When you use Cscript.exe to run this script, the output is displayed in a comma-delimited text file named C:\Scripts\Newhosts.csv. You can open a .csv file as a spreadsheet. Output similar to the following is displayed on the monitor when the script runs.

C:\scripts>dns-move.vbs

 

Host: client1

 

 

Host: client2

 

 

Host: server1

 

Inventory complete. Data written to c:\scripts\newhosts.csv.

Tools for Scripting DNS on Clients

Table 17 outlines the available Windows tools to use for scripting DNS on clients.

Table 17   Tools for Scripting DNS on Clients

Technology

Tool

Where Available

Command-line tools

Dnscmd.exe: DNS Server Troubleshooting Tool

Windows Server 2003 Support Tools

Command-line tools

Dnslint.exe

Windows Server 2003 Support Tools

Command-line tools

DNSRECORD.PL

Windows 2000 Resource Kit

Command-line tools

DNSSERVER.PL

Windows 2000 Resource Kit

Command-line tools

DNSZONES.PL

Windows 2000 Resource Kit

Command-line tools

NETDNSCONFIG.PL

Windows 2000 Resource Kit

Command-line tools

Netsh.exe

Windows operating systems1

Command-line tools

Nslookup.exe

Windows operating systems

WSH

None

 

WMI

Win32_ComputerSystem

 

WMI

Win32_OperatingSystem

 

WMI

Win32_NetworkAdapterConfiguration

 

WMI

Win32_NTDomain

Windows XP and Windows Server 2003 only

1 Windows 2000, Windows XP, and Windows Server 2003. May also be present on other versions of Windows.

Table 18 outlines the available registry subkeys to use for scripting DNS on clients.

caution.gif  Caution
Incorrectly editing the registry may severely damage your system. Before making changes to the registry, you should back up any valued data on the computer.

Table 18   Registry Subkeys Related to Scripting DNS on Clients

Registry Subkeys

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\Interfaces
\{AdapterIdentifier}

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Dnscache