在逃生窗批处理文件中用户输入 [英] Escape user input in windows batch file
问题描述
我有一个接受口令作为用户输入Windows批处理文件:
I have a windows batch file that accepts a password as user input:
SET /P PASSWORD=Password:
此密码可能有需要转义像人物!
。在密码
变量,然后被传递给使用调用其他批处理文件
This password might have characters that need escaping like !
. The PASSWORD
variable then gets passed to other batch files using CALL
CALL Foo.Bat %PASSWORD%
我怎样才能确保特殊字符转义得到正确传递为参数?例如,如果用户输入%!£$
我想%1
是 %!£$
在 Foo.bat
。
推荐答案
这是一个很好的挑战,但是这是一批先进工艺。结果
我会在这里用一个简单的方法,使用延迟扩展和不发送的内容,只有变量名。
It's a nice challenge, but this is advanced batch technic.
I would use here a simpler way, use delayed expansion and do not send the content, only the variable name.
这是绝对安全的,即使有特殊字符。
This is absolute safe even with special characters.
call foo.bat password
Foo.bat -----------------
Foo.bat -----------------
Setlocal EnableDelayedExpansion
Echo !password!
编辑:为解决原来的问题,结果
这是与所述内容而不是变量名来解决它的方法强>
这是必要的prepare内容的通过CALL到第二批文件发送的它。结果
很难使用类似 CALL foo.bat%preparedVariable%
结果
它似乎是更好地使用 CALL foo.bat!preparedVariable!
结果
但即使如此,我不行了,脱字由CALL相加倍。
It's necessary to prepare the content before sending it via CALL to second batch file.
It's hard to use something like CALL foo.bat %preparedVariable%
It's seems to be better to use CALL foo.bat !preparedVariable!
But even then I fail at the doubling of carets by the CALL-phase.
但后来我发现用百分比扩张只是CALL-阶段之后的简单方法。
But then I found a simple way to use the percent expansion just after the CALL-phase.
@echo off
setlocal DisableDelayedExpansion
rem set /p "complex=Complex Input "
set "complex=xx! & "!^&"ab^^ " ^^^^cd%%"
setlocal EnableDelayedExpansion
call :prepareForCallBatch complex PreparedParam
echo Send =!PreparedParam!#
set complex
echo(
call ShowParam.bat %%PreparedParam%%
exit /b
:: Prepare special characters &|<>"^ for a batch call
:prepareForCallBatch
set "temp=!%~1!"
set "temp=!temp:^=^^!"
set "temp=!temp:&=^&!"
set "temp=!temp:|=^|!"
set "temp=!temp:<=^<!"
set "temp=!temp:>=^>!"
set "temp=!temp:"=^^"!"
set "%~2=!temp!"
exit /b
要看到的真正的在ShowParam.bat参数我用的是这样的结果
的 ShowParam.bat 的
To see the real parameters in ShowParam.bat I use something like this
ShowParam.bat
@echo off
setlocal
set prompt=
@echo on
REM # %* #
这篇关于在逃生窗批处理文件中用户输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!