【问题标题】:What is wrong with goto command in for loop?for循环中的goto命令有什么问题?
【发布时间】:2014-08-03 09:28:50
【问题描述】:

我有一个计算机列表,我想根据 tcp 连接状态做一些事情。
我正在尝试检查 tcp 连接,如果错误日志为“1”,则写入行记录并跳到下一台计算机。
问题是当一台计算机没有 tcp 连接时,goto skip_action 命令会将脚本带到末尾并退出,而列表中的其他计算机则未处理。 我也尝试过使用goto :eof,它意外终止了脚本。

ipst.txt file:
1     10.1.1.10
3     10.1.3.10
8     10.1.3.10

这是批处理文件代码:

@echo off
setlocal enabledelayedexpansion 
set computerslist=ipst.txt

for /f "usebackq tokens=1,2" %%A in ("%Computerslist%") do (
    cls
    set Station_Num=%%A
    set Comp_IP=%%B
    ping !Comp_IP! -n 1 | findstr "TTL"     
    if !errorlevel!==1 (
        echo Station !Station_Num! .... !Comp_IP! ..................... No Communication.>>%log%
        goto skip_action
    )
    echo Getting Administrator Credentials:
    net use \\!Comp_IP! /USER:WORKGROUP\****** ******
    echo.
    xcopy file.txt  \\!Comp_IP!\c\temp\
    echo Disconneting Session From Remote Computer :
    net use \\!Comp_IP! /DELETE /YES    
    :skip_action
    echo end of working on !Station_Num!
)

echo end of script

【问题讨论】:

    标签: batch-file goto


    【解决方案1】:

    这里的问题是 GOTO 取消了 for 循环。
    但是您可以简单地将您的操作包含在 ELSE 块中

    
    for /f "usebackq tokens=1,2" %%A in ("%Computerslist%") do (
        cls
        set Station_Num=%%A
        set Comp_IP=%%B
        ping !Comp_IP! -n 1 | findstr "TTL"     
        if !errorlevel!==1 (
            echo Station !Station_Num! .... !Comp_IP! ..................... No Communication.>>%log%
    
        ) Else (
        echo Getting Administrator Credentials:
        net use \\!Comp_IP! /USER:WORKGROUP\****** ******
        echo.
        xcopy file.txt  \\!Comp_IP!\c\temp\
        echo Disconneting Session From Remote Computer :
        net use \\!Comp_IP! /DELETE /YES    
        )
        echo end of working on !Station_Num!
    )
    

    【讨论】:

    • @Ohad_E 编辑您的问题并使用 ELSE 块添加您的代码。
    【解决方案2】:

    if - else 语句的一般形式

       If condition (
    
       Statements
    
       ) else (
    
       Statements to be executed if condition is not met 
    
       )
    

    【讨论】:

      【解决方案3】:

      从循环中拨打电话

      你可以有一个函数 ping .. 并解析对它的变量引用 .. 前面的代码也可以呈现为 %%a 和 %%b 分别作为第一个和第二个参数——在你的函数调用中......

         Call :pingcomputers %%a %%b
      

      这样你就可以完全避免设置

         :pingcomputers
      

      Rem Ping 计算机 %~1

         Ping %~2 ¦ find "reply"
         If errorlevel 1 goto failed
         (Actions to be performed if ping wa successful)
      

      假设您的脚本有一个标签 failed 并且如果错误级别不为 0 则要执行的操作 ..

      脚本不多,但希望对您有所帮助...

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-04-23
        • 2018-12-08
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多