Vidya Sagar
Vidya Sagar

Reputation: 133

Parse multiple arguments inside a batch file.

I would like to read two parameters that are passed to a batch file. The batch file will be executed from a C++ program using CreateProcess method. The second parameter to the batch file is a folder path, so from the program if I am passing the second parameter such as "E:\test folder\test2" the batch file does not get executed.

But if I instead pass E:\test folder\test2 the batch file gets executed but obviously the second parameter has the value E:\test only.. So what I would like to do is to read the first parameter using %1 and get the rest of the contents into another variable.

Can some one tell me how I can achieve this ? I tried with %* but it gives me both first and second parameters. I would like to remove the first token with space as delimiter so that I have the rest of the contents in the variable. Is there a way to do this ?

For example If I pass test.bat testparameter1 E:\test folder\test folder2\test folder3

I would like to read the value E:\test folder\test folder2\test folder3 into a variable.

If I pass test.bat testparameter1 E:\test\test folderX\test folderY the valueIi want to read in to a variable inside the batch file is E:\test\test folderX\test folderY

Can someone help me with this ? Thanks in advance.

Upvotes: 0

Views: 3743

Answers (2)

Aacini
Aacini

Reputation: 67216

Could you change spaces in the path by another character in your C++ code? For example, if we change spaces by arroba, then you could pass this:

test.bat testparameter1 E:\test@folder\test@folder2\test@folder3

and in the Batch file do the opposite change this way:

set param2=%2
set param2=%param2:@= %

Another possible method is to collect all the parameters from the second one on in the same variable, separating each one by one space:

set param1=%1
shift
set param2=
:nextParam
set param2=%param2% %1
shift
if not "%1" == "" goto nextParam

Upvotes: 2

Ken White
Ken White

Reputation: 125669

If your batch file is called with

test.bat testparam1 "E:\test\folder2\test folder 3"

You can read the parameters using %1 and %2

rem Contents of test.bat
@echo %0
@echo %1
@echo %2

The above produces:

C:\Temp>test testparam1 "E:\test\folder2\test folder 3"
test.bat
testparam1
"E:\test\folder2\test folder 3"

C:\Temp>

So you already have the parameters as variables; they're called %1 for the first one, %2 for the second, and so forth.

If the problem is that you're trying to do something using the "E:\test\folder2\test folder 3" path, just make sure you add a trailing backslash before passing it in:

"E:\test\folder2\test folder 3\"

Upvotes: 0

Related Questions