-
The most straightforward way to create reusable code in a batch file is using a subroutine.
@ECHO OFF CALL :PrintHeader "Disk Check Utility" CALL :PrintHeader "Log Cleaner" GOTO :EOF :PrintHeader ECHO. ECHO ============================ ECHO %1 ECHO ============================ ECHO. EXIT /B
:PrintHeadercan be reused to print a formatted title anywhere.%1allows passing in a dynamic value.
-
You can build modular utility libraries at the bottom of your script.
@ECHO OFF CALL :LogInfo "Script started" REM Your main logic here... CALL :LogInfo "Script ended" GOTO :EOF :: ------------------------------- :: Logging Utilities :: ------------------------------- :LogInfo ECHO [INFO] %~1 EXIT /B :LogError ECHO [ERROR] %~1 EXIT /B
💡 Use
::or REM to group utility sections clearly. -
You can create reusable
.batlibraries by keeping utility subroutines in a separate file and calling it from multiple scripts.@ECHO OFF GOTO :EOF :LogInfo ECHO [INFO] %~1 EXIT /B :LogError ECHO [ERROR] %~1 EXIT /B
@ECHO OFF CALL utils.bat CALL :LogInfo "Started main script" REM More logic CALL :LogError "Something went wrong" GOTO :EOF
⚠️ You mustCALLthe file and make sure it doesn't execute its own labels unless specifically called. -
@ECHO OFF CALL :Add 15 25 result ECHO Sum is: %result% CALL :Multiply 5 10 result ECHO Product is: %result% GOTO :EOF :Add SETLOCAL SET /A temp=%1 + %2 ENDLOCAL & SET %3=%temp% EXIT /B :Multiply SETLOCAL SET /A temp=%1 * %2 ENDLOCAL & SET %3=%temp% EXIT /B
This pattern simulates returning a value via a third parameter.
-
Need multiple outputs? You’ll have to use multiple variable names.
@ECHO OFF CALL :DivideAndRemainder 10 3 result remainder ECHO Quotient: %result% ECHO Remainder: %remainder% GOTO :EOF :DivideAndRemainder SETLOCAL SET /A q=%1 / %2 SET /A r=%1 %% %2 ENDLOCAL & ( SET %3=%q% SET %4=%r% ) EXIT /B
-
If you want a more abstract way to call code blocks dynamically:
@ECHO OFF SET task=LogStart CALL :%task% SET task=LogEnd CALL :%task% GOTO :EOF :LogStart ECHO Starting process... EXIT /B :LogEnd ECHO Process complete. EXIT /B
Useful for command dispatchers or menu-based systems.