Using 'functions' in batch files

Learn how to use 'functions' in batch files in this user-submitted tip.

More on Windows systems management

Learn how to trace open files on a shared network.

Have a Windows systems management tip? Submit it. You could receive an Amazon gift certificate.
Did you know that there are ways to use 'functions' in batch files? SearchWincomputing.com member Jim Ruby submitted this Windows systems management tip explaining how to do so.

It is possible to create function-like structures in WIN32 cmd files to break apart and simplify long batch files. One batch file can call another and use the returned value as a variable for further steps.

Granted, there are times when this method is overkill, but there are plenty of opportunities to use this technique. Believe it or not, you can actually create some structured programming in cmd files using this concept.

The three cmd files code examples below demonstrate this idea. The main batch file that will call and display the results of Function1.cmd and Function2.cmd is called Calc.cmd. Both "functions" return values to The Calc cmd file; Function1 returns one value while Function2 return two values.

TheCalc.cmd
-----------

@Echo off
FOR /F %%f in ('Function1') do SET TheAnswer=%%f ECHO.
ECHO.
ECHO.
ECHO The Answer is: %TheAnswer%
ECHO.
ECHO.
ECHO.


FOR /F "Tokens=1-2 delims= " %%g in ('Function2') DO (SET TheAnswer1=%%g & SET TheAnswer2=%%h)
ECHO.
ECHO.
ECHO.
ECHO The 1st Answer is: %TheAnswer1%
ECHO The 2nd Answer is: %TheAnswer2%M
ECHO.
ECHO.
ECHO.


Function1.cmd

-------------
SET /A Function1=2+4
ECHO %Function1%


Function2.cmd

-------------
SET /A Function1=2+4
SET /A FirstAnswer=1+1
SET /A SecondAnswer=2+2
ECHO %FirstAnswer% %SecondAnswer%

Rating this tip below will let us know how useful it was to you. And if you have a Windows tip, timesaver or workaround to share, submit it to our tip contest. You could win the prize for that contest.

This was first published in March 2007

Dig deeper on Windows File Management

Pro+

Features

Enjoy the benefits of Pro+ membership, learn more and join.

0 comments

Oldest 

Forgot Password?

No problem! Submit your e-mail address below. We'll send you an email containing your password.

Your password has been sent to:

SearchServerVirtualization

SearchCloudComputing

SearchExchange

SearchSQLServer

SearchWinIT

SearchEnterpriseDesktop

SearchVirtualDesktop

Close