如何在批处理文件中使用数组?

How to use array in batch file?

我正在尝试重命名我电脑上的 NIC 名称。它有很多 NIC(它们是虚拟的)。我可以这样得到他们的名字

for /f "tokens=2 delems==" %%A in ('wmic nic where "Description like 'foo'" get netconnection id /value') do (
 echo %%A
)

我想在该循环中使用 netsh 来重命名它们。不幸的是,目标名称不是简单的递增数字。所以我做了

set names[0]=name1
set names[1]=name two
set names[2]=name test
set local ENABLEDELAYEDEXPANSION
set /a idx=0
for /f "tokens=2 delems==" %%A in ('wmic nic where "Description like 'foo'" get netconnectionid /value') do (
 echo names[!idx!]
 set /a idx=!idx!+1
)

这输出

names[0]
names[1]
names[2]

但如果我尝试

set names[0]=name1
set names[1]=name two
set names[2]=name test
set local ENABLEDELAYEDEXPANSION
set /a idx=0
for /f "tokens=2 delems==" %%A in ('wmic nic where "Description like 'foo'" get netconnectionid /value') do (
 echo %names[!idx!]%
 set /a idx=!idx!+1
)

我只是得到垃圾输出。有什么方法可以将上一个示例中生成的字符串作为变量求值吗?然后我可以将其传递给 netsh 进行重命名。

首先,您的代码有几个错误。这一行:

set local ENABLEDELAYEDEXPANSION

...应该这样写:

setlocal ENABLEDELAYEDEXPANSION

否则 "setlocal" 命令变成 "set" 命令,并且不会以相同的方式工作。

这一行:

for /f "tokens=2 delems==" %%A in (. . .

...选项必须写成 "delims=="(不是 "delems=="),但在这种情况下,FOR 命令会发出错误。

修复这些错误后,您应该使用this answer中完整描述的方法访问数组元素,所以我将相关部分复制到这里:

To get the value of an element when the index changes inside FOR/IF, enclose the element in double percent symbols and precede the command with call:

call echo %%names[!idx!]%%

Another way to achieve the previous process is to use an additional FOR command to change the delayed expansion of the index by an equivalent replaceable parameter, and then use the delayed expansion for the array element. This method runs faster than previous CALL:

for %%i in (!idx!) do echo !names[%%i]!

我最终找到了一种方法来执行此操作,但它仅在尝试对数字数组进行索引时才有效。这是我用的

@ECHO OFF
set names[1]=101
set names[2]=102
set names[3]=103

setlocal ENABLEDELAYEDEXPANSION

set /a idx=1
for /L %%A in (1,1,3) do (
 set /a foo = names[!idx!] #This is the key, for some reason, an intermediate variable is required.
 echo !foo!
 set /a idx=!idx!+1
)