我有一个Windows批处理文件,可以接受用户输入的密码:
SET /P PASSWORD=Password:
这个密码可能包含需要转义的特殊字符,如!
。然后将PASSWORD
变量传递给其他批处理文件使用CALL
。
CALL Foo.Bat %PASSWORD%
我该如何确保特殊字符被转义并作为参数正确传递?例如,如果用户输入 !%"£$"
,我希望在 Foo.bat
中 %1
是 !%"£$"
。
我有一个Windows批处理文件,可以接受用户输入的密码:
SET /P PASSWORD=Password:
这个密码可能包含需要转义的特殊字符,如!
。然后将PASSWORD
变量传递给其他批处理文件使用CALL
。
CALL Foo.Bat %PASSWORD%
我该如何确保特殊字符被转义并作为参数正确传递?例如,如果用户输入 !%"£$"
,我希望在 Foo.bat
中 %1
是 !%"£$"
。
这是一个不错的挑战,但这是高级批处理技术。
我会使用一种更简单的方法,使用延迟扩展并且只发送变量名而不是内容。
即使存在特殊字符,这也是绝对安全的。
call foo.bat password
Foo.bat -----------------
Setlocal EnableDelayedExpansion
Echo !password!
编辑:关于原问题的解决方案,以下是一种使用内容而非变量名来解决的方法
在通过CALL命令将内容发送到第二个批处理文件之前,需要准备好内容。使用类似CALL foo.bat %preparedVariable%
这样的方式难以实现。使用CALL foo.bat !preparedVariable!
似乎更好,但即使如此,在CALL阶段也会出现插入多个尖角符号的问题。@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
@echo off
setlocal
set prompt=
@echo on
REM # %* #
Echo !%~1!
,因为变量的名称被作为参数传递。 - dbenham