0

I'm trying to make a batch file that sets my DNS settings to local host if they are something else, and automatic if they are localhost. What I made so far is:

set var=1

if "%var%" == "1"
(
netsh interface ipv4 add dnsserver "Wi-Fi" address=127.0.0.1 index=1
set var=2
)

if "%var%" == "2"
(
netsh interface ip set dns “Wi-Fi” dhcp
set var=1
)

pause

Clearly, the variables are not permanent and don't "save". That's problem number 1. However, this script won't even change it to the localhost address. Additionally, if it did work the script has the clear setback of not detecting if the DNS settings have been changed by some other mean. I'm stuck, as my google-fu is not up to the challenge of figuring out what I'm doing wrong.

1 Answers1

1

The opening parenthesis in the if command must be in the same line that the if command

No, environment variables are not "saved". Each process has its own copy of the environment variables, and changes made from one process are not visible from the others. The value in the variable remains as long as the process that sets it, or until the process removes its value. To persist the variable you need to explicitly save it to the registry (see setx /?) or to a file (that you will later have to read).

And, your code has a logic error. in batch files, code is executed from one line to the next unless something change it, so

if %var%==1 (
    change to state 1
    set var=2
)
if %var%==2 (
    change to state 2
    set var=1
)

There is nothing preventing the execution leaving the first if enter the second one. When this code executes, it will always change to state 2.

It should be easier to detect the current state and then change to the other

netsh interfave ipv4 show dnsservers "Wi-Fi" | find "DHCP" > nul
if errorlevel 1 (
    netsh interface ipv4 set dnsservers "Wi-Fi" dhcp
) else (
    netsh interfave ipv4 add dnsservers "Wi-Fi" address=127.0.0.1 index=1
)

The first netsh command reads the current configuration and the find searchs for the string "DHCP". If it is not found (errorlevel==1) change configuration to dhcp, else (see the parenthesis placement, see here) change configuration to local dns server

Community
  • 1
  • 1
MC ND
  • 69,615
  • 8
  • 84
  • 126