Read Mode
Default

Functionality of Functions in Batch Code - Batch File Function with Parameters

It is commonly thought that Batch code does not support functions. However, this is simply not true. Batch coding has a built-in function feature that people often use in all their scripts without even knowing it. Today I'm going to go over how and when to use functions in your batch script.

Functionality of Functions in Batch Code - Batch File Function with Parameters

The Functionality of Functions - Batch File Function with Parameters

There are some basic aspects that you need to know, For Creating your own Functions in Batch. You can make all kinds of batch functions from a simple one to a complex one. And, the functions are not limited to Pure Batch. You can also use various available Plugins to enhance the Function's timing and performance etc. Let's have a look at various aspects of the Batch Functions.

Colons Gotos and Calls:

Almost every batch coder is familiar with the GOTO Command, and it's brother the colon. Now what might surprise you is that GOTO is not a feature Microsoft thought coders would use as much as they do when they added it in. Originally there was only going to be the CALL command, which was how you would call functions. See the following example:


@echo off
echo Hello
echo this is my time function:
call :myTimeFunction
pause
exit

:myTimeFunction
echo The Time is %time%
exit /b


OUTPUT:

Functionality of Functions in Batch Code - Batch File Function with Parameters
Functionality of Functions in Batch Code - Batch File Function with Parameters
Microsoft decided to add in the GOTO command so that coders could go to a function without going back. However, the call function still exists today. It can not only be used to call batch files, but functions just like the above example!

How do you use functions? - Defining Batch functions

A function consists of three required parts. They are:
  1. a label
  2. a script
  3. An end
The label in our example script was :myTimeFunction. Just like GOTO labels, a function label is marked with a colon. The script is simply the code you wish to run, and the end is where you mark the end of your function. You can mark the end of a function with the EXIT /B command. When the script hits this part it will return to where you called the function.
Functionality of Functions in Batch Code - Batch File Function with Parameters
Functionality of Functions in Batch Code - Batch File Function with Parameters

Advanced Features of Functions

There are many more parts you can add to your function such as:
  1. Variables
  2. ErrorLevels
  3. Function Files

Variables

Variables are perimeters you can add to your function. Take the following example:


:DateTimeFunction
if “%1”==”” echo The Date is %Date% The Time is %time%
if /i “%1”==”/D” echo the Date is %Date%
if /i “%1”==”/T” echo the Time is %time%
exit /b

This Function uses a special variable with only one percentage: %1. These special variables are the parameters you enter when you call your function. For Example: CALL :DateTimeFunction /D. This would give you the date since %1 is equal to /D.



Each new parameter (separated by spaces or by quotes) has a new number. When using parameters there are three main points you need to remember:
  1. You can have unlimited parameters (%1 %2 %3 %4 ...etc)
  2. Parameters must be separated by spaces or quotes: (Example: CALL :Function Option1 Option2 or CALL :Function “Option one” “option two”).
  3. Parameters variables cease to exist once you end the function.
Parameters can be used in many ways. You can have custom text output, you can have different settings, and it can even lead to more advanced functions like ones that add multiple colors to a Command Prompt Window.

Error Levels

Error Levels are very useful in batch coding. Any batch coder should already know what the %ERRORLEVEL% variable is, it simply shows whether an error occurred when a command was run. If not, it is set to zero. If it was, it is set to one, or two, or any number depending on the type of error.

In functions, you can set the error level with the EXIT /B command. Check out this example script which has a function which copies Files: 


@echo off
echo Copying File Function
echo Please Enter the File to Copy to Downloads.
set /p file=">"
Call :CopyFile %file%
if %errorlevel%==1 echo File not found
if %errorlevel%==2 echo File was a folder.
If %errorlevel%==0 echo Complete.
Pause
exit


:CopyFile
::Checks if file exists
if not exist %1 exit /b 1
setlocal EnableDelayedExpansion
::Removes quotes from file name if there are any
set fle=%1
set File=%Fle:"=%
::Checks if file is actually a folder
if exist "%File%\*.*" exit /b 2
copy "%File%" "C:\users\%username%\Downloads\" >nul
exit /b 0

Now some of this script may be a little beyond you, and that's okay. What I want you to look at is the EXIT /B commands. The numbers after the /B set the errorlevel.

If there is no number it leaves the errorlevel as it was before. This allows you to easily handle errors uniquely in different sections of your script, while using the same basic function for all of them. See the example Here:

Functionality of Functions in Batch Code - Batch File Function with Parameters
The functionality of Functions in Batch Code - Batch File Function with Parameters
It tested if the file was a folder, and when it was, it set the Error Level to two. Thus, the code new to say "File Was a Folder". Error Levels can also be used for uses other than errors. You can set the errorlevel to the count of scripts like in this example function:


:CountFiles
for /f %%A in ('dir /a-d-s-h /b %1 ^| find /v /c “”`) do set count=%%A
exit /b %count%

You would call this script with the command CALL :CountFiles “C:\Path\”.

Function Files

Function Files are files that store your functions. This is especially useful if you have a set of scripts that all use the same functions. You start your function file with this at the top of it:


@echo off
set Function=%1
shift
call %Function% %1 %2 %3 %4 %5 %6 %7 %8 %9
exit /b %errorlevel%

For example's sake we shall call it Functions.bat, however, you can name it any .bat or .cmd file. and then you add all your functions after those three lines. Then, inside another script you can call it like this: CALL Functions.bat :FunctionName Parameters. 



It will accept up to nine parameters and should work exactly as it would if it was in your script. The shift command in there is an important command that "shifts" all of the parameters down one. So %1 is deleted, %2 becomes %1, %3 becomes %2 and so on.

This allows you to send 9 parameters to the file as well as the function (10 total parameters). I also like to add a list of functions to my function file, but that is totally optional. Consider the following example:


REM Functions.bat:

@echo off
set Function=%1
shift
call %Function% %1 %2 %3 %4 %5 %6 %7 %8 %9
exit /b %errorlevel%

:CountFiles
for /f %%A in ('dir /a-d-s-h /b %1 ^| find /v /c “”`) do set count=%%A
exit /b %count%

REM Another script:

@echo off
echo Enter a Folder to count files in
echo (include quotes if necessary):
set /p Folder=”>”
call Functions.bat :CountFiles %Folder%
echo %errorlevel% Files
pause
exit

So you can see how functions can be really useful and extensive in batch coding.

A Comment on Plugins

Plugins are similar to batch files in that you call them. Plugins are usually .exe files written in another language than batch (often C, C#, Python, Java etc.) that work within the console. Plugins like the commonly discussed Batbox.exe offer more possibilities.

They are basically extra commands you can use from within your batch program. The benefit of using functions over plugins is that they do not require separate files, can easily be debugged and customized, and don't set off anti-viruses as easily as plugins do.

In Closing - From Editor's Desk

In closing, I hope you have grown to appreciate how well functions work in batch codes. While they may not be as extensive as in other coding languages, with a little effort you can get just as much done in Batch. Keep coding, and continue to check with TheBATeam for more articles and updates!


No comments:

Powered by Blogger.