我正在尝试编写一个脚本来读取用户输入,以便为 IP 管理器进行选择,但在将一个变量格式化为另一个变量的索引时遇到了问题。我尝试了很多不同的方法,但还没有成功。
@setlocal enableextensions enabledelayedexpansion
@echo off
cd %~dp0
set OPT=
set CLN=
if exist IPManCfg.cmd (
call IPManCfg.cmd
) else (
echo Active Network Adaptors:
set /a fc=1
for /F "skip=3 tokens=1,2,3* delims= " %%G in ('netsh interface show interface') DO (
set OPT[!fc!]=%%J
echo [!fc!] %%J
set /a fc+=1
)
set /P CLN="Please select the listed adaptor: "
echo you've selected !CLN! which is !!OPT[!CLN!]!!
endlocal
输出为:
您选择了 2,即 CLN
答案1
您应该尝试添加另一个循环For /L
和条件,如以下代码:
@echo off
@setlocal enableextensions enabledelayedexpansion
cd %~dp0
set OPT=
set CLN=
echo Active Network Adaptors:
set /a fc=1
@for /F "skip=3 tokens=1,2,3* delims= " %%G in ('netsh interface show interface') DO (
set OPT[!fc!]=%%J
echo [!fc!] %%J
set /a fc+=1
)
set /P CLN="Please select the listed adaptor: "
@for /L %%i in (1,1,%fc%) do (
If "!CLN!" EQU "%%i" (
echo you've selected !CLN! which is "!OPT[%%i]!"
)
)
pause
endlocal
答案2
以下是可能的编码的一个简短示例。
这些编码也可用于例如“set”命令,而不是“echo”命令。
@echo off
setlocal enableextensions enabledelayedexpansion
REM --- prepare some data ---
set IDX=2
set "STRING[%IDX%]=my string"
REM --- possible codings for data output ---
echo 1: !STRING[%IDX%]!
echo 2: !!STRING[%IDX%]!!
call echo 3: !!STRING[%IDX%]!!
call echo 4: %%STRING[!IDX!]%%
REM this works also without 'enableextensions' and 'enabledelayedexpansion'
call echo 5: %%STRING[%IDX%]%%
exit /b 0