CMD在参数中嵌套双引号

时间:2012-09-23 11:13:25

标签: batch-file cmd command-line-arguments double-quotes

我遇到了使用嵌套双引号将参数传递给批处理函数的问题。

以下是批处理文件的示例:

@SET path_with_space="c:\test\filenamewith space.txt"
@CALL :FUNCTION blaat1, "blaat2 %path_with_space%"
@GOTO :EOF

:FUNCTION
@echo off
echo arg 1: %~1
echo arg 2: %~2
echo arg 3: %~3
GOTO :EOF

输出结果为:

arg 1: blaat1
arg 2: blaat2 "c:\test\filenamewith
arg 3: space.txt""

我应该怎样做arg 2: blaat2 "c:\test\filenamewith space.txt"? 请注意,我无法调整功能或更改%path_with_space%。我只能控制传递给函数的内容。

5 个答案:

答案 0 :(得分:11)

就像dbenham所说的那样,如果没有引号,参数中的空格似乎是不可能的 但是,如果您知道接收器函数如何获取参数,则可能会出现这种情况 然后你可以通过一个转义的延迟变量转移参数,变量将不会在调用中扩展,它将在函数中展开。
并且有必要将函数中的参数分配给变量,但这可能是一个良好且可读的代码中的情况。

setlocal EnableDelayedExpansion 
set path_with_space="c:\test\filenamewith space.txt"
@CALL :FUNCTION blaat1, "blaat2 ^!path_with_space^!"
GOTO :EOF

:FUNCTION
@echo off
echo arg 1: %~1
echo arg 2: %~2
echo arg 3: %~3
GOTO :EOF 

输出结果为:

arg 1: blaat1
arg 2: blaat2 "c:\test\filenamewith space.txt"
arg 3:

编辑:批量注射

即使应始终禁用延迟扩展,这也有效 但是接下来你需要在函数中扩展参数。

@echo off
set path_with_space="c:\test\filenamewith space.txt"
CALL :FUNCTION 1 2 ""^^"&call:inject:""
exit/b

:inject
set arg1=blaat1
set arg2=blaat2 %path_with_space%
set arg3=none
exit /b

:FUNCTION
@echo off
set "arg1=%~1"
set "arg2=%~2"
set "arg3=%~3"
echo arg 1: %arg1%
echo arg 2: %arg2%
echo arg 3: %arg3%
GOTO :EOF

答案 1 :(得分:2)

我发现了这一点,但我所能做的就是将问题转移到不同的区域。

Working with Quotes

@SET 

path_with_space="c:\test\filenamewith space.txt"

:: Remove quotes
@SET _string=###%path_with_space%###
@SET _string=%_string:"###=%
@SET _string=%_string:###"=%
@SET _string=%_string:###=%

@echo %_string%

@CALL :FUNCTION blaat1, "blaat2 %_string%"
@GOTO :EOF

:FUNCTION
@echo off
@echo arg 1: %~1
@echo arg 2: %~2
@echo arg 3: %~3

:EOF


pause

答案 2 :(得分:2)

我认为不可能。

无法转义空格,使其不被解释为参数分隔符。在参数中包含空格的唯一方法是将其括在引号中。你需要一些空间来引用,有些则不需要,所以这是不可能的。

答案 3 :(得分:1)

@jeb +1

@davor

为什么不使用双引号

@SET path_with_space=""c:\test\filenamewith space.txt""
@CALL :FUNCTION blaat1, "blaat2 %path_with_space%", blaat3
@GOTO :EOF

:FUNCTION
@echo off
echo arg 1: %~1
::--------------------
set arg2=%~2
set arg2=%arg2:""="%
::-------------------
echo arg 2: %arg2%
echo arg 3: %~3
GOTO :EOF 

输出结果为:

arg 1: blaat1
arg 2: blaat2 "c:\test\filenamewith space.txt"
arg 3: blaat3

答案 4 :(得分:0)

  

如果您不想使用延迟扩展(您需要编辑FUNCTION来完成此操作!):

我建议您在将参数传递给 FUNCTION (在原始示例中注意%path_with_space:"=%" vs %path_with_space%")之前删除引号然后您可以将它们放回去替换您的路径引用的版本(%%_arg_2:%path_with_space:"=%=%path_with_space%%%):

@SET path_with_space="c:\test\filenamewith space.txt"
@CALL :FUNCTION blaat1, "blaat2 %path_with_space:"=%"
@GOTO :EOF

:FUNCTION
@echo off
echo arg 1: %~1
set _arg_2=%~2
call echo arg 2: %%_arg_2:%path_with_space:"=%=%path_with_space%%%
echo arg 3: %~3
GOTO :EOF

输出是:

arg 1: blaat1
arg 2: blaat2 "c:\test\filenamewith space.txt"
arg 3:

如果其他参数还包含引号中包含的路径,则可以对所有参数使用相同的模式