【问题标题】:batch file load balacing code query批处理文件负载均衡代码查询
【发布时间】:2014-02-11 19:35:03
【问题描述】:

我正在尝试从以下参考中运行 bat 文件代码:

Detecting batch IP conflict

但是,我收到一个错误: TRUE - 无效的别名动词 此时 -1 是出乎意料的。

请有人向我解释一下。谢谢。下面附上示例代码

     @echo off
    setlocal

    :: Host to ping
    set primary=x.x.x.1
:: Ping with options (1 ping sent per loop, wait 500 ms for timeout)
set ping_options=-n 1 -w 500
:: Fail over after x ping failed responses
set fail_limit=5

:loop

    :: Ping x.x.x.1.  Test for "reply from".  If success, set failures=0; otherwise, increment failures
( ping %ping_options% %primary% 2>&1 | find /i "reply from" >NUL && set failures=0 ) || set /a "failures+=1"

:: If failures >= limit, switch IP
if failures GEQ %fail_limit% call :switch

:: Pause for a second and begin again.
ping -n 2 0.0.0.0 >NUL
goto loop


:: Switch subroutine
:switch

:: Get current IPv4 address
for /f "tokens=2 delims={}," %%I in ('wmic nicconfig where ipenabled="TRUE" get ipaddress /format:list') do set IP=%%~I

:: If the last character if the current IP is 1, switch to 2 (or vice versa)
if %IP:~-1%==1 ( set other=%IP:0,-1%2 ) else set other=%IP:0,-1%1

:: Perform the switch
netsh int ipv4 set address name="Local Area Connection" source=static address=%other% mask=255.255.255.0 gateway=none

【问题讨论】:

    标签: networking batch-file


    【解决方案1】:

    您需要做的就是将 wmic 命令中的等号转义。

    for /f "tokens=2 delims={}," %%I in (
        'wmic nicconfig where ipenabled^="TRUE" get ipaddress /format:list'
    ) do set IP=%%~I
    

    【讨论】:

    • 嗨,这是否意味着 ipenabled 不等于 true?
    • @LionelKoh,不。 for /f 命令的命令部分受到解析器工作方式的“影响”。等号之前的插入符号是一个转义字符,表示解析器不应解析下一个字符,而是按原样包含。没有它,等号将从命令中删除,并生成“动词”错误。如果没有等号(被删除),“TRUE”子句将被解释为 wmic 的另一个命令。
    • 您好,请您也向我解释一下这条线。感谢您的帮助 if %IP:~-1%==1 ( set other=%IP:0,-1%2 ) else set other=%IP:0,-1%1
    • @LionelKoh,如果你单独运行wmic命令,你会得到一个机器中的ip地址列表。此列表提供给for 命令。对于wmic 的输出中的每一行,使用字符{}, 作为分隔符(字符串被切割成片段的点),取第二个标记(片段),将其存储到 %%I 并执行下面的代码do。请记住,所有这些都是针对内部命令输出 (wmic) 中的每一行完成的。如果它返回多于一行,则第二行及后续的迭代将覆盖存储在%IP% 中的值。
    • 非常感谢您的帮助
    猜你喜欢
    • 1970-01-01
    • 2021-04-29
    • 2015-09-30
    • 1970-01-01
    • 2012-07-15
    • 1970-01-01
    • 2021-12-07
    • 2020-10-06
    • 2013-05-01
    相关资源
    最近更新 更多