Reputation: 853
I'm currently writing a simple batch script to set the DNS of a LAN connection automatically. Here is the script:
REM Set DNS
netsh interface ip set dns name="Local Area Connection" static X.X.X.X
netsh interface ip add dns name="Local Area Connection" Y.Y.Y.Y index=2
netsh interface ip add dns name="Local Area Connection" Z.Z.Z.Z index=3
But the thing is, if the Local Area Network name is not default (i.e. Local Area Connection), the script will not work.
Is there any way I can detect all the Local Area Connection names and set all of those LAN connections' DNS using the batch file?
Any help will be appreciated :)
Upvotes: 2
Views: 21568
Reputation: 1
Windows XP 1st line output of command 'netsh int ip show config' is:
Configuration for interface "Local Area Connection"
@echo off
for /F tokens^=2^ delims^=^" %%a in ('netsh int ip show config') do set "sUserFriendyName=%%a"
echo/set http://www.opendns.com/ DNS for interface "%sUserFriendyName%"
netsh int ip delete dns "%sUserFriendyName%" all
netsh interface ip set dns name="%sUserFriendyName%" source=static addr=208.67.222.222 register=PRIMARY
netsh interface ip add dns name="%sUserFriendyName%" addr=208.67.220.220 index=2
ipconfig /flushdns
Upvotes: 0
Reputation: 12814
I've tested this code in Windows 7. You may need to make some modifications for Windows XP.
@Echo Off
For /f "skip=2 tokens=4*" %%a In ('NetSh Interface IPv4 Show Interfaces') Do (
Call :UseNetworkAdapter %%a "%%b"
)
Exit /B
:UseNetworkAdapter
:: %1 = State
:: %2 = Name (quoted); %~2 = Name (unquoted)
If %1==connected (
:: Do your stuff here, for example:
Echo %2
)
Exit /B
I'll just note that I always use Call
statements rather than bracketed script. Too often people become confused when environment variables don't behave as expected in bracketed script. I find calling a label makes script easier to work with.
EDIT: Explination.
The For
command reads each line of a file or command result.
In ('command')
tells it to read each line of the results of command
.
skip=2
skips the first two lines of output, in this case, the column header.
tokens=4*
says to read the fourth thing on each line as one variable (4
), and everything after that as another variable (*
).
%%a
says to store the above tokens in %%a
and %%b
respectively.
Do (commands)
executes the commands
for each line.
My output of NetSh Interface IPv4 Show Interface
is:
Idx Met MTU State Name
--- ---------- ---------- ------------ ---------------------------
1 50 4294967295 connected Loopback Pseudo-Interface 1
15 50 1500 disconnected Bluetooth Network Connection
24 10 1500 connected Network Bridge
So I take the fourth token (the State) and all tokens after that (the Name) and pass them to a script function call. Here they are retrieved as command line parameters, namely %1
and %2
.
Note that each Name consists of two or three tokens because of the spaces, hence using *
instead of 5
.
Upvotes: 9