Page 1 of 1

FOR loop which calls subroutine ?

Posted: 08 Nov 2011 08:09
by DavePC
Hello,

I'm trying to create a batch file which uses a FOR loop to update multiple files in mulitple directories on multiple servers.

To test whether this is possible I have created a simplified version of the batch file but cannot get it to run.

If I use the following code the loop is cycled through for each of the servers and the correct output it produced

@ECHO OFF
SET SID=ABC
FOR %%A IN (server1 server2 server3 server4 server5 server6 server7) DO (
ECHO Delete Old %SID% Backup files on %%A
ECHO Backup Current %SID% Files on %%A
ECHO Copy New %SID% files to %%A
)

If I try to branch out of the FOR loop though and use a sub-routine called LOOP it does not work.

@ECHO OFF
SET SID=ABC
FOR %%A IN (server1 server2 server3 server4 server5 server6 server 7) DO (goto loop)
:loop
ECHO Delete Old %SID% Backup files on %%A
ECHO Backup Current %SID% Files on %%A
ECHO Copy New %SID% files to %%A

and only the following output is produced

Delete Old ABC Backup files on %A
Backup Current ABC Files on %A
Copy New ABC files to %A

I have tried multiple versions of batch file without success. Ideally I would like to use the FOR loop and called sub-routine process.

Within Batch files is it possible to branch out of a FOR loop ?
Is it possible to pass the %%A value to a variable i.e. SET servername=%%A ?
Can anyone suggest some code based on the FOR loop and called sub-routine that might work ?

Many thanks,

Re: FOR loop which calls subroutine ?

Posted: 08 Nov 2011 08:43
by dbenham
You need to use CALL instead of GOTO (see HELP CALL) and the FOR variable needs to be passed as a parameter because the scope is only within the loop:

Code: Select all

@ECHO OFF
SET SID=ABC
FOR %%A IN (server1 server2 server3 server4 server5 server6 server 7) DO (call :loop %%A)
exit /b
:loop
ECHO Delete Old %SID% Backup files on %1
ECHO Backup Current %SID% Files on %1
ECHO Copy New %SID% files to %1
exit /b


Dave Benham