FOR循环无法正常执行

时间:2014-01-02 20:32:52

标签: batch-file for-loop

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

server1的
服务器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并且在批处理命令之后逐个执行servername时,它在没有FOR循环的情况下工作正常。 THX!

1 个答案:

答案 0 :(得分:3)

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  
  )
)