创建批处理文件以标识活动的Internet连接

时间:2011-03-25 17:18:14

标签: windows batch-file dos

我正在尝试编写一个批处理文件,如果netsh命令生成的列表中有多个,则允许用户选择其活动的Internet连接,然后更改DNS设置。

但是,在执行脚本之前,当知道选项数量时,我无法弄清楚如何使用choice命令。在没有使用数组的情况下,我试图创建一个字符串变量'choices'来保存表示数字选择的字符串并将其传递给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

1 个答案:

答案 0 :(得分: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 /?

解释