I think a lot of Windows command batch scripters are not aware that you can call an internal procedure within a batch file. I sure did not find out about it until about 3-4 years ago.
Anyway, to get this work, 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.
:MyProc
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 all 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
:RunBatch
Set servername=%1
perform action 1
perform action 2…
goto :EOF
:end
exit
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.