2011-03-25 69 views
2

我试图编写一个批处理文件,这将允许用户选择他们的活动Internet连接,如果有多个来自netsh命令生成的列表,然后更改DNS设置。创建一个批处理文件来识别活动的Internet连接

但是我不知道如何使用选择命令时,已知的选项数量,直到脚本执行。没有使用数组,我试图创建一个字符串变量'choices'来保存代表数字选择的字符串,并将它传递给选择命令,但是我不能让它工作。我不禁感到必须有一个更简单的方法来做到这一点,但我的研究没有向我证明这一点。任何帮助将受到感谢。

@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 

回答

2

问题不在于选择命令,选择字符串的构建失败。
有时一个简单的echo on会有所帮助。

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

这失败,因为set choices=%choices%展开一次循环开始前,所以你有set choices=1%%G

而是可以使用延迟扩展

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

或双/呼叫膨胀

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

延迟扩展与set /?

被(部分地)说明