【发布时间】:2015-09-05 14:54:11
【问题描述】:
尝试做:
fake-command.bat "ping -n 4 -w 1 127.0.0.1 >NUL"
和
fake-command.bat ping -n 4 -w 1 127.0.0.1
批处理文件可能如下所示:
@echo %*
它应该返回:
ping -n 4 -w 1 127.0.0.1 >NUL
和
ping -n 4 -w 1 127.0.0.1
这里有一个解决方法:
@echo off
goto start
------------------------------------------------------
Usage : mystring <command>
Quotes around the command are required only when the
command involves redirection via <, >, >>, or |, etc.
Quotes ensure that the redirection is applied to the
command, rather than the bat command itself.
Examples :
mystring ping -n 4 -w 1 127.0.0.1
mystring "ping -n 4 -w 1 127.0.0.1 >NUL"
------------------------------------------------------
:start
SETLOCAL ENABLEDELAYEDEXPANSION
SET "MYSTRING=%*"
ECHO My String = !MYSTRING!
SET !MYSTRING=MYSTRING:>=^>!
CALL :BATCH_FUNCTION !MYSTRING!
GOTO :EOF
:BATCH_FUNCTION
SET "ARGS=%~1"
ECHO Arguments = !ARGS!
endlocal
GOTO :EOF
问题在于:mystring "ping -n 1 127.0.0.1 >NUL"
返回:
My String =
Arguments =
及之后:mystring ping -n 1 127.0.0.1
返回:
My String = ping -n 1 127.0.0.1
Arguments = ping
更新: 我用Get list of passed arguments in Windows batch script (.bat)的以下代码更新了这个问题
@echo off
SETLOCAL DisableDelayedExpansion
SETLOCAL
if exist param.txt (del param.txt)
for %%a in ('%*') do (
set "prompt="
echo on
for %%b in ('%*') do rem * #%~1#
@echo off
) > param.txt
ENDLOCAL
for /F "delims=" %%L in (param.txt) do (
set "param1=%%L"
)
SETLOCAL EnableDelayedExpansion
set "param1=!param1:*#=!"
set "param1=!param1:~0,-2!"
echo My string is = !param1!
使用此代码,我可以获得转义字符,但参数不在引号中的输出被破坏
什么有效?
mystring "# % $ ` ' ( ) < << >> > >NUL && & || | { } \ / - + = , . : ; ^ " &REM OK
mystring "ping -n 4 -w 1 127.0.0.1 >NUL" &REM OK
返回:
My string is = # % $ ` ' ( ) < << >> > >NUL && & || | { } \ / - + = , . : ; ^
My string is = ping -n 4 -w 1 127.0.0.1 >NUL
什么不起作用?
mystring ping -n 4 -w 1 127.0.0.1 &REM NOK
mystring "*" &REM NOK
返回:
My string is = ping
The system can not find the file param.txt.
My string is = *
我看不出如何在这段代码中添加the trick from Mofi。
【问题讨论】:
-
1) 你把Get list of passed arguments in Windows batch script (.bat)的代码改得太多了。您不应该在 FOR 循环中放置
%*,参数的唯一位置是在REM后面,例如REM # %* #。 2)您的第二个示例无法工作,因为&REM NOK将由命令行实例执行,它不会作为参数传输。你可以用引号(就像你做的那样)或插入符号^& REM转义它
标签: windows batch-file escaping