Change DNS with script

Primary DNS value:

netsh interface ipv4 set dns "Local Area Connection" static 192.168.0.2

Secondary value:

netsh interface ipv4 add dns "Local Area Connection" 192.168.0.3 index=2

Which works great IF the name of the connection is correct. If the name isn't "Local Area Connection" then it will not work. If you are running XP you need to change "ipv4" to "ip". IPv6 can be used too.

Set subnet mask, IP Address, and Gateway:

netsh interface ipv4 set address name="Local Area Connection" source=static addr=192.168.1.10 mask=255.255.255.0 gateway=192.168.0.1

To Find the network connection you can use ipconfig from the cmd line. But you can also use the following for an abbreviated ipconfig result:

ipconfig | find /I "Ethernet adapter"

using the above ipconfig cmd we can loop through the connection (source code) and set the dns servers:

:: Set primary and alternate DNS for IPv4 on Windows Server 2000/2003/2008 & 
:: Windows XP/Vista/7
@ECHO OFF
SETLOCAL EnableDelayedExpansion

SET adapterName=

FOR /F "tokens=* delims=:" %%a IN ('IPCONFIG ^| FIND /I "ETHERNET ADAPTER"') DO (
SET adapterName=%%a

REM Removes "Ethernet adapter" from the front of the adapter name
SET adapterName=!adapterName:~17!

REM Removes the colon from the end of the adapter name
SET adapterName=!adapterName:~0,-1!

netsh interface ipv4 set dns name="!adapterName!" static 192.168.0.2 primary
netsh interface ipv4 add dns name="!adapterName!" 192.168.0.3 index=2
)

ipconfig /flushdns

:EOF

Also to use DNS addresses provided by the DHCP server:

netsh interface ipv4 set dns "Local Area Connection" dhcp

Here is your new friend: QuickSetDNS, by NirSoft, amazing as usual.

screenshot

It also can be used in command line :) with these advantages over netsh:

  • easier syntax, in particular for setting the alternate server
  • automatically asks for privilege elevation


Just a few caveats:

  • supports only setting of IPv4, not of IPv6
    • since QuickSetDNS 1.30, setting IPv6 DNS servers is also supported ;)
  • in command line, the adapter UUID should be used, not the friendly name (e.g. "Local Area Connection")