user275373
user275373

Reputation: 35

FOR loop doesn't execute properly

I'm running into an odd issue with a batch file. I want to run the following commands on a set of servers using a FOR loop. The list of servers is -

server1
server2
server3
server4
in file "servers.txt" which is in the same folder as the batch file. The batch file is -

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  
)  

The resulting output is -

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.  

The command completed successfully.

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

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

It seems to only pick up the first entry from the txt file and even then does not execute properly. It worked fine without the FOR loop when I used a %1 parameter in place of the %%A one and executed with the servername after the batch command on a one by one basis. Thx!

Upvotes: 2

Views: 374

Answers (1)

jeb
jeb

Reputation: 82418

A GOTO always terminates all FOR-loops or leaves all blocks.
Independent of the position of the label.

So the GOTO has to be replaced by an IF .. ELSE statement.

So your code could be changed to something like

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

Upvotes: 3

Related Questions