athanell
athanell

Reputation: 25

Passing an argument from one batch file to another

I have 2 batch files.

The first one needs an input argument which is a path of a parent folder. It reads the names of all subfolders inside the parent folder and executes the second batch file for each subfolder.

BATCH FILE 1

@echo off
for  /d %%Y in (%1/*) do (  
set SubfolderNameAndPath=%%Y
call batch2.bat %SubfolderNameAndPath% 
)

The second batch file uses as input argument the SubfolderNameAndPath and executes an Evaluate.exe for all the files that exist in each subfolder. It saves the results of the Evaluate.exe to a text file "results" with an extension that carries the name of the subfolder that each time has been accessed. (results_%~n1.txt).

BATCH FILE 2

@echo off
for  %%X in (%1/*) do (  
echo Evaluate.exe  %%X AnotherArgumentHere -o results_%~n1.txt   
)

When I run the batch1 (batch1.bat ParentFolderPath) even if it seems to call the batch2.bat, the batch2.bat is not executed. I believe that something goes wrong with the way that I define the input arguments for the batch2.bat but I cannot figure out what it is.

The %SubfolderNameAndPath% does not contain any spaces. Neither the path to the folder does. I would really appreciate your help on that.

Upvotes: 0

Views: 4374

Answers (1)

James K
James K

Reputation: 4055

Well, first, when inside a bracketed pair you can't set a variable then access it with the %'s. You must first (before the for loop) setlocal enabledelayedexpansion, then access your variables with the !'s rather than the %'s.

But since you do not do anything with %SubfolderNameAndPath% anyway, you should just eliminate it.

Second, you need to compensate for paths containing spaces, so hopefully my code below will work out for you. To do this, batch uses a special notation for arguments passed to to remove double quotes around them. So, if %1 = "This string", then %~1 = This string. Also, if %1 = This string, then %~1 still = This string. So there is no drawback to using the %~1 notation, unless you want to retain any double quotes.

So, int batch1.bat, we remove any potential quotes surrounding %1, and then place double-quotes around %~1/*, and also double-quote %%Y just in case there are spaces in it.

batch1.bat

@echo off
for  /d %%Y in ("%~1/*") do call batch2.bat "%%~Y"

Then we do the same thing for batch2.bat, but more of it.

batch2.bat

@echo off
for  %%X in ("%~1/*") do (
  echo Evaluate.exe  "%%~X" AnotherArgumentHere -o "results_%~n1.txt"
)

EDIT: 2012/09/05 15:21

How's this grab you? Instead of calling a seprate batch:

for /d %%x in (%1\*) do (
  for /f "tokens=*" %%y in ( 'dir /b /a:-d "%%~dpnxx"' ) do (
    echo Evaluate.exe %%~nxy AnotherArgumentHere -o "results_%%~nxx.txt" 
  )
)

(The above can be put all on one line, just remove the brackets.)

I'm assuming the output is:
Evaluate.exe <file_name> AnotherArgumentHere -o "results_<directory_name>.txt"

Upvotes: 1

Related Questions