CMD: Calling internal procedures in a batch file

16 May

I was not aware that one could create a procedure within a batch to call it until some 3-4 years ago.  To get this working, first you must create a procedure. A procedure is like any standard batch script except that you must enclose it with a label at the head and goto label at the foot.


set myname=%1

@echo this is my first procedure

@echo my name is %1

goto :EOF

The start of the procedure is defined by the label :MyProc. A label always begins with a semi-colon. If you are accepting arguments in your procedure, you should treat it like a normal arguments, i.e. %1, %2, etc. You must end the procedure with a goto :EOF statement, if you don’t the procedure will continue running any commands below it.

To call the procedure, do a call :Label, in the example above I would call the procedure with call :MYProc JohnDoe.

At this point in time, this don’t seem very useful to you. However, imagine if you have to loop through a list of servers and execute a batch job on them or if you have a switchboard type of batch file and it runs different procedure based on what the user chose, then this becomes very powerful indeed.

In my work, I have such a batch file that automates the disk alignment, formatting and reporting of new SAN disks on a SAN connected server via an input list

Here is a simple but useful example:

for /f %%a in (servers.txt) do call :RunBatch %%a

goto end


Set servername=%1

perform action 1

perform action 2…

goto :EOF



You would also notice that I have added a goto end before the procedure, this is to prevent the batch or your own mistake for running through the entire batch file.

Leave a comment

Posted by on May 16, 2008 in Scripts, Windows CMD



Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: