变量.1 此时出乎意料



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

@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

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

所以代码似乎是

FOR /L nicNameAA%.1

因此,cmd看到了nicNameAA%.1它期待%%?的地方并抱怨。

顺便说一句,由于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!