is there anything that mimicks a method like one knows it from Java, C# etc.? I have 5 lines of commands in a batch file, those 5 lines are used at more than one place insid
I'm not sure if it was obvious from other answers but just to be explicit I'm posting this answer. I found other answers helpful in writing below code.
echo what
rem the third param gives info to which label it should comeback to
call :myDosFunc 100 "string val" ComeBack
:ComeBack
echo what what
goto :eof
:myDosFunc
echo. Got Param#1 %~1
echo. Got Param#2 %~2
set returnto=%~3
goto :%returnto%
Just for completeness, you can also pass parameters to the function:
Function call
call :myDosFunc 100 "string val"
Function body
:myDosFunc
echo. Got Param#1 %~1
echo. Got Param#2 %~2
goto :eof
Placing the reusable functions into a separate batch file would certainly work to simulate a function.
The catch is that you have to use the call
command in order to ensure that control returns to the caller after the second batch file finishes executing.
call 5lines.bat
echo this will now get called
You could use the call command :
call:myDosFunc
And then define the function this way :
:myDosFunc - here starts the function
echo. here the myDosFunc function is executing a group of commands
echo. it could do a lot of things
goto:eof
Source : Batch Functions
For another great tutorial on writing reusable batch file code -- see Richie Lawrence's excellent library.
Solution:
@ECHO OFF
call:header Start Some Operation
... put your business logic here
... make sure EXIT below is present
... so you don't run into actual functions without the call
call:header Operation Finished Successfully
EXIT /B %ERRORLEVEL%
:: Functions
:header
ECHO =================================================
ECHO %*
ECHO =================================================
EXIT /B 0
Important to put EXIT /B at the end of each function, as well as before function definitions start, in my example this is:
EXIT /B %ERRORLEVEL%