开发者

Creating a batch file to identify the active Internet connection

Im trying to write a batch file which will allow a user to select their active Internet connection if there is more than one from a list generated by the netsh command and then change the DNS settings.

However I can't figure out how to use the choice command when the number of options are known until the script is executed. Without the开发者_JAVA技巧 use of arrays, I have tried to create a string variable 'choices' to hold the string representing the numerical choices and pass it to the choices command, but I cant get it to work. I can't help feeling that there must be a much easier way to do this but my research fails to show me so. Any help would be gratefully received.

@echo off
setlocal
Set active=0
Set choices=1
set ConnnectedNet=
FOR /F "tokens=2,3* " %%j in ('netsh interface show interface ^| find "Connected"') do Set /A active+=1
FOR /L %%G IN (2,1,%active%) do (set choices=%choices%%%G)
if %active% lss 2 goto :single
if %active% gtr 1 goto :multiple
:single
FOR /F "tokens=2,3* " %%j in ('netsh interface show interface ^| find "Connected"') do set ConnnectedNet=%%l
netsh interface IPv4 set dnsserver "%ConnnectedNet%" static 0.0.0.0 both
goto :eof
:multiple
echo You have more than one active interface. Please select the interface which you are using to connect to the Internet
FOR /F "tokens=2,3* " %%j in ('netsh interface show interface ^| find "Connected"') do echo %%l
CHOICE /C:%choices% /N /T:1,10


The problem is not at the choice command, the building of the choice-string fails.
Sometimes a simple echo on would help.

set choices=1
...
FOR /L %%G IN (2,1,%active%) do (set choices=%choices%%%G)

This fails, because the set choices=%choices% is expanded only once before the loop starts, so you got set choices=1%%G.

Instead you could use delayed expansion

setlocal EnableDelayedExpansion  
FOR /L %%G IN (2,1,%active%) do (set choices=!choices!%%G)

or double/call expansion

FOR /L %%G IN (2,1,%active%) do (call set choices=%%choices%%%%G)

The delayed expansion is (partially) explained with set /?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜