batch-file Functions

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Remarks

You can add starting variables to the function by adding <parameter> to it's label. These starting variables can be accessed with %n where n is the starting variable's number (%1 for the first, %2 for the second. This %n method works for %1 - %9. For parameter 10 - 255, you will need to use the Shift command).
For example:

:function <var1> <var2>

Once you use call :function param1 param2, param1 can be accessed with %1, and param2 with %2.
Note: the <parameter> isn't strictly necessary, but it helps with readability.

A neat trick that is useful when many variable are flying about is to use setlocal and endlocal in tandem with %n. setlocal and endlocal essentially make the function it's own separate instance of the command prompt, variables set in it only stick around while it's in the frame.

If you are using setlocal and endlocal, and you are returning global values use this.

endlocal & set var=variable

This sets the global value var to variable. You can chain these together for multiple variables.

endlocal & set var=variable & set var2=variable number 2

This sets the global variable var to variable and the global value var2 to variable number 2.
Since code in code blocks are also performed simultaneously, you can do this as well.

if "%var%"=="" (
    endlocal
    set %~2=10
)

But, you cannot do this.

if "%var%"=="" (
    set %~2=10
    endlocal
)


Got any batch-file Question?