Configure DNS search order (VBScript)

This code can be found in Chapter 1 of Windows Server 2003 Networking Recipes

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.

' From the book "Windows Server 2003 Networking Recipes"

' This code will add a DNS server with the IP address of
' 192.168.1.151 to the beginning of the DNS search order
' ------ SCRIPT CONFIGURATION ------
strComputer = "."
strNewDNSServer = "192.168.1.151"
' --------- END CONFIGURATION ------

Set objWMIService = GetObject("winmgmts:" _
 & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set nics = objWMIService.ExecQuery _
 ("SELECT * FROM Win32_NetworkAdapterConfiguration WHERE IPEnabled = True")

For Each nic  In nics
  ' grab the current DNS search order
  arrDNSServerOrder = nic.DNSServerSearchOrder

  ' create a new array to hold the current DNS servers, plus one new one
  intNewArraySize = UBound(arrDNSServerOrder) + 1
  ReDim Preserve arrDNSServerOrder(intNewArraySize)

  ' Count backwards from the end of the array back to the first
  ' element, which is at index (0)
  For i = (intNewArraySize - 1) To 0 Step -1
    ' Move each element one index "higher" in the array
    arrDNSServerOrder(i + 1) = arrDNSServerOrder(i)
  Next

  ' Add the new server to index (0) of the array
  arrDNSServerOrder(0) = strNewDNSServer
  intNewDNS = nic.SetDNSServerSearchOrder(arrDNSServerOrder)
  If intNewDNS = 0 Then
    WScript.Echo "Success!! Added " & strNewDNSServer & _
     " to the top of the DNS search order."
  Else
    WScript.Echo "Error!! Unable to change DNS server search order."
  End If
Next

This code has been viewed 3023 times.

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