【问题标题】:FOR loop doesn't execute properlyFOR 循环没有正确执行
【发布时间】:2014-01-02 20:32:52
【问题描述】:

我在批处理文件中遇到了一个奇怪的问题。我想使用 FOR 循环在一组服务器上运行以下命令。服务器列表是 -

服务器1
服务器2
服务器3
服务器4
在文件“servers.txt”中,该文件与批处理文件位于同一文件夹中。批处理文件是 -

for /f "delims=" %%a in (servers.txt) do (  
net use y: /delete  
net use y: \\%%a\d$  
if exist "y:\Program Files\%%a\file.txt" goto STAGE  
echo Does not exist for %%a  
goto END  

:STAGE  
echo Exists for %%a  

:END  
net use y: /delete  
)  

结果输出是 -

H:\>for /F "delims=" %a in (servers.txt) do (  
net use y: /delete  
 net use y: \\%a\d$  
 if exist "y:\Program Files\%a\file.txt" goto STAGE  
 echo Does not exist for %a  
 goto END  
 echo Exists for %a  
 net use y: /delete  
)  

H:\>(   
net use y: /delete  
 net use y: \\server1\d$  
 if exist "y:\Program Files\server1\file.txt" goto STAGE  
 echo Does not exist for server1  
 goto END  
 echo Exists for server1  
 net use y: /delete  
)  

The network connection could not be found.    
More help is available by typing NET HELPMSG 2250.  

命令成功完成。

H:\>echo Exists for %a  
Exists for %a  

H:\>net use y: /delete  
y: was deleted successfully.  

它似乎只从 txt 文件中提取第一个条目,即使那样也不能正确执行。当我使用 %1 参数代替 %%A 参数并在批处理命令之后使用服务器名逐一执行时,它在没有 FOR 循环的情况下工作正常。谢谢!

【问题讨论】:

    标签: batch-file for-loop


    【解决方案1】:

    GOTO 总是终止所有 FOR 循环或离开所有块。
    与标签的位置无关。

    所以GOTO 必须替换为IF .. ELSE 语句。

    因此您的代码可以更改为类似

    for /f "delims=" %%a in (servers.txt) do (  
      net use y: /delete  
      net use y: \\%%a\d$  
      if exist "y:\Program Files\%%a\file.txt" (
        echo Exists for %%a  
        net use y: /delete  
      ) ELSE (
        echo Does not exist for %%a  
      )
    )  
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-11-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多