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 🙂
I’ve tested this code in Windows 7. You may need to make some modifications for Windows XP.
I’ll just note that I always use
Callstatements 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
Forcommand reads each line of a file or command result.In ('command')tells it to read each line of the results ofcommand.skip=2skips 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 (*).%%asays to store the above tokens in%%aand%%brespectively.Do (commands)executes thecommandsfor each line.My output of
NetSh Interface IPv4 Show Interfaceis: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
%1and%2.Note that each Name consists of two or three tokens because of the spaces, hence using
*instead of5.