变量1此时意外

时间:2018-01-29 17:56:50

标签: windows batch-file wmic netsh

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

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

提前致谢!

2 个答案:

答案 0 :(得分:0)

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%是未指定的环境变量{{1 }}

  3. 您的代码的结果是

    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 ......只是做好准备。

答案 1 :(得分:0)

正如@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!