Variable.1 此时意外

Variable.1 unexpected at this time

我只是想弄清楚为什么这段代码会给我一个意想不到的变量..

@echo off
FOR /F "Skip=1Delims=" %%a IN (
    '"wmic nic where (MacAddress="00:00:00:00:00:00") GET NetConnectionId"'
) DO FOR /F "Tokens=1" %%b IN ("%%a") DO SET nicName=%%b

echo Adding all IP ranges for X in 10.10.X.118 on adapter %nicName%
netsh interface ipv4 set address name=%nicName% static 192.168.1.118 255.255.255.0 192.168.1.1
FOR /L %A IN (0,1,255) DO netsh interface ipv4 add address %nicName% 10.10.%A%.118 255.255.255.0 10.10.%A%.1
netsh interface ipv4 add dnsserver %nicName% address=208.67.222.222 index=1
netsh interface ipv4 add dnsserver %nicName% address=208.67.220.220 index=2

exit

我认为这与第一个 FOR 循环干扰第二个有关,但我对在批处理文件中使用这种类型的搜索还很陌生。

我得到的输出是:

Adding all IP ranges for X in 10.10.X.118 on adapter Local Area Connection
nicNameAA.1 was unexpected at this time.

提前致谢!

FOR /L %A IN (0,1,255) DO netsh interface ipv4 add address %nicName% 10.10.%A%.118 255.255.255.0 10.10.%A%.1
  1. 与前两个for命令一样,元变量 A必须指定为%%A

  2. 和前面两个for命令一样,代入字符串的值必须指定为%%A - %A%是未指定环境的值变量 A.

你的代码的结果是这样的

FOR /L 
%A IN (0,1,255) DO netsh interface ipv4 add address %
nicName
% 10.10.%
A
%.118 255.255.255.0 10.10.%
A
%.1

每个 %...% 都被解释为不存在的环境变量,因此它被替换为 nothing

所以代码看起来

FOR /L nicNameAA%.1

所以 cmd 看到 nicNameAA%.1 它期望 %%? 的地方并抱怨。

BTW- 由于 nicname 的值包含空格,您可能需要 "%nicname%" 以便 cmd 将看到一个字符串。不能保证,因为我很少使用 netsh...请做好准备。

@Magoo 的回答, 生成的完整代码如下(以防以后有人需要这样做)

@echo off
FOR /F "Skip=1Delims=" %%a IN (
    '"wmic nic where (MacAddress="00:00:00:00:00:00") GET NetConnectionId"'
) DO FOR /F "Tokens=1" %%b IN ("%%a") DO SET nicName=%%b

echo Adding all IP ranges for X in 10.10.X.118 on adapter "%nicName%"
netsh interface ipv4 set address name="%nicName%" static 192.168.1.118 255.255.255.0 192.168.1.1
FOR /L %%c IN (0,1,255) DO netsh interface ipv4 add address "%nicName%" 10.10.%%c.118 255.255.255.0 10.10.%%c.1
netsh interface ipv4 add dnsserver "%nicName%" address=208.67.222.222 index=1
netsh interface ipv4 add dnsserver "%nicName%" address=208.67.220.220 index=2

exit

再次感谢@Magoo!