FOR loop which calls subroutine ?

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
DavePC
Posts: 1
Joined: 08 Nov 2011 06:54

FOR loop which calls subroutine ?

#1 Post by DavePC » 08 Nov 2011 08:09

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,

dbenham
Expert
Posts: 2461
Joined: 12 Feb 2011 21:02
Location: United States (east coast)

Re: FOR loop which calls subroutine ?

#2 Post by dbenham » 08 Nov 2011 08:43

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

Post Reply