Dav*_*vic 9 cmd batch-file 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
Run Code Online (Sandbox Code Playgroud)
输出是:
arg 1: blaat1
arg 2: blaat2 "c:\test\filenamewith
arg 3: space.txt""
Run Code Online (Sandbox Code Playgroud)
我该怎么做arg 2: blaat2 "c:\test\filenamewith space.txt"?请注意,我无法调整功能或更改%path_with_space%.我只能控制传递给函数的内容.
jeb*_*jeb 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
Run Code Online (Sandbox Code Playgroud)
输出是:
arg 1: blaat1
arg 2: blaat2 "c:\test\filenamewith space.txt"
arg 3:
Run Code Online (Sandbox Code Playgroud)
编辑:批量注射的溶剂
即使应始终禁用延迟扩展,这仍然有效.
但是现在你需要在函数中如何扩展参数.
@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
Run Code Online (Sandbox Code Playgroud)