Creating a batch file to identify the active Internet connection

人盡茶涼 提交于 2020-01-23 03:17:24

问题


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 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

回答1:


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 /?



来源:https://stackoverflow.com/questions/5435884/creating-a-batch-file-to-identify-the-active-internet-connection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!