Rotan075
Rotan075

Reputation: 2615

Create function out of parameters

Hello I got a question regarding functions within a batch file. I have the following setup:

echo off
set dSource=%1
set dTarget=%2
set fType=%3
for /f "delims=" %%f in ('dir /a-d /b /s %dSource%\%fType%') do (
    copy /V "%%f" %dTarget%\tempsrc 2>nul
)

I can call this batch file with the following parameters:

test.bat "C:\Batch" "C:\Output" "text.xml"

Is there a posibility that I can have, like in Javascript or any other programming language, a function which takes the parameter as input so that I can make a call like this:

functionName(dSource,dTarget,fType1)
functionName(dSource,dTarget,fType2)
etc..

Otherwise I have to do it like this:

for /f "delims=" %%f in ('dir /a-d /b /s %dSource%\%fType1%') do (
    copy /V "%%f" %dTarget%\tempsrc 2>nul
)
for /f "delims=" %%f in ('dir /a-d /b /s %dSource%\%fType2%') do (
    copy /V "%%f" %dTarget%\tempsrc 2>nul
)

Which is very insufficient

Upvotes: 1

Views: 75

Answers (2)

Jeff Zeitlin
Jeff Zeitlin

Reputation: 10764

Batch files do not have true functions (in the sense of returning a value); they do, however, have the equivalent of procedures or subroutines, which can take parameters. Subroutines/procedures are invoked by the CALL command. If you do not need to pass information back to the caller from the callee, the CALLed routine may be stored in a separate .BAT or .CMD file; if you need to pass information back (a "function hack"), the subroutine must be a labelled block in the caller file. For the latter, see the DOSTips Batch Function Tutorial.

(For what it's worth, I do agree with Bill_Stewart's recommendation for using PowerShell in preference to batch.)

Upvotes: 2

npocmaka
npocmaka

Reputation: 57252

You can do with label which you can invoke with call ::label:

call ::funct param_1 param_2

exit /b %errorlevel%

:funct [dsource ftype]
echo off
set dSource=%1
set dTarget=%2
set fType=%3
for /f "delims=" %%f in ('dir /a-d /b /s %dSource%\%fType%') do (
    copy /V "%%f" %dTarget%\tempsrc 2>nul
)

And you need to set exit /b before starting functions definitions in order to prevent them to execute twice.

Upvotes: 2

Related Questions