在 Windows 批处理文件中转义用户输入

2023-12-13

我有一个 Windows 批处理文件,它接受密码作为用户输入:

SET /P PASSWORD=Password:

该密码可能包含需要转义的字符,例如!. The PASSWORD然后使用变量将其传递给其他批处理文件CALL

CALL Foo.Bat %PASSWORD%

如何确保特殊字符被转义并作为参数正确传递?例如如果用户输入!%"£$" I want %1 to be !%"£$" in Foo.bat.


这是一个很好的挑战,但这是先进的批处理技术。
我在这里会使用一种更简单的方法,使用延迟扩展并且不发送内容,仅发送变量名称。

即使使用特殊字符,这也是绝对安全的。

call foo.bat password

Foo.bat -----------------

Setlocal EnableDelayedExpansion
Echo !password!

编辑:原始问题的解决方案,
这是一种用内容而不是变量名来解决它的方法

之前需要准备好内容sending它通过调用第二个批处理文件。
很难使用类似的东西CALL foo.bat %preparedVariable%
使用起来似乎更好CALL foo.bat !preparedVariable!
但即便如此,我在 CALL 阶段的插入符号加倍还是失败了。

但后来我发现了一种简单的方法,可以在 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

为了看到realShowParam.bat 中的参数我使用类似的东西
显示参数.bat

@echo off
setlocal
set prompt=
@echo on
REM # %* #
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 Windows 批处理文件中转义用户输入 的相关文章

随机推荐