简体   繁体   中英

windows command line pass through quotes

I have a command that I want to pass into a batch file that contains quotes. What i want to do is pass in the following parameter as a single parameter into the bat file:

set parameter=-c myfirstparameter -p "also my first parameter"

C:\mybat.bat parameter

Unfortunatly this ends up being:

%1 = -c
%2 = myfirstparameter
etc

What I want is

%1 = -c myfirstparameter -p "also my first parameter"

You cannot do what you want. Batch uses [space], [comma], [semicolon], [equal], [tab], and [0xFF] as token delimiters when parsing arguments. If you want a token delimiter literal within an argument value, then the delimiter must be quoted. It is impossible to escape a token delimiter. Therefore it is impossible to have a single parameter that has both quoted and unquoted token delimiter literals.

Presumably the top code in your question is wrong. In order to get the results you describe, you must have

set parameter=-c myfirstparameter -p "also my first parameter"
C:\mybat.bat %parameter%

The best way to handle such a situation is to pass your parameter by reference, which requires a modification to your mybat.bat.

Instead of retrieving the value via %1 , you must enable delayed expansion and use !%1!

@echo off
setlocal enableDelayedExpansion
set "argument1=!%1!"

With such an arrangement, you would indeed use the following to call the script:

set parameter=-c myfirstparameter -p "also my first parameter"
C:\mybat.bat parameter

Here is a working example of using a temp file ( as found here ) to pass the parameter:

FIRST.BAT

echo -c myfirstparameter -p "also my first parameter">dummy.txt
second.bat

SECOND.BAT

set /p param=<dummy.txt
echo %param%

Here is the raw output:

C:\temp\batchtest>first

echo -c myfirstparameter -p "also my first parameter" 1>dummy.txt

second.bat

set /p param= 0<dummy.txt

echo -c myfirstparameter -p "also my first parameter"
-c myfirstparameter -p "also my first parameter"

C:\temp\batchtest>

You need to quote the parameter. Please try these in a simple, test .bat script.

echo %*
echo %1
echo %~1
set IT=%~1
echo %IT%

set IT=%*
echo %IT%
echo %IT:~1,-1%

c:> y.bat "-p arf "asdfasdf asdfasdf""

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM