9/03/2008

vbScript to automatically changing a specific DNS Server on all Servers

The following vbScript replaces a specific DNS Server IP with another one, independed if the IP is the Primary or Secondary DNS Server.

Dim objFSO : Set objFSO = CreateObject("Scripting.FileSystemObject")
Dim objShell : Set objShell = CreateObject("Wscript.Shell")
Dim objFile : Set objFile = objFSO.OpenTextFile("c:\computers.txt")
Dim strOldIP : strOldIP = "1.1.1.1"
dim strNewIP : strNewIP = "2.2.2.2"
Dim arrDNSServer(2)
dim i : i = 0

Do While Not objFile.AtEndOfStream
currentserver = objFile.ReadLine
Set objWMIService = GetObject("winmgmts:" & "{impersonationLevel=impersonate}!\\" & currentserver & "\root\cimv2")
Set colNicConfigs = objWMIService.ExecQuery ("SELECT * FROM Win32_NetworkAdapterConfiguration WHERE IPEnabled = True")

For Each objNicConfig In colNicConfigs
If Not IsNull(objNicConfig.DNSServerSearchOrder) Then
For Each strDNSServer In objNicConfig.DNSServerSearchOrder
arrDNSServer(i) = strDNSServer
i=i+1
Next
End If
Next

If arrDNSServer(0) = strOldIP Then
'Changing the primary dns server
objShell.Run "netsh -r " ¤tserver &" interface ip set dnsserver " &chr(34) &"local area connection" &Chr(34) &" static " &strNewIP &" primary",1,True
objShell.Run "netsh -r " ¤tserver &" interface ip delete dnsserver " &chr(34) &"local area connection" &Chr(34) &" " &arrDNSServer(1),1,True
objShell.Run "netsh -r " ¤tserver &" interface ip add dns " &chr(34) &"local area connection" &Chr(34) &" " &arrDNSServer(1) &" index=2",1,True
ElseIf arrDNSServer(1) = strOldIP Then
'Changing the secondary DNS Server
objShell.Run "netsh -r " ¤tserver &" interface ip delete dnsserver " &chr(34) &"local area connection" &Chr(34) &" " &arrDNSServer(0),1,True
objShell.Run "netsh -r " ¤tserver &" interface ip set dnsserver " &chr(34) &"local area connection" &Chr(34) &" static " &arrDNSServer(0) &" primary",1,True
objShell.Run "netsh -r " ¤tserver &" interface ip add dns " &chr(34) &"local area connection" &Chr(34) &" " &strNewIP &" index=2",1,True
End If
i = 0
Loop

No comments: