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%
How can I ensure that special characters get escaped and passed correctly as parameter? For example if the user inputs !%"£$"
I want %1
to be !%"£$"
in 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 -----------------
Setlocal EnableDelayedExpansion
Echo !password!
EDIT: Solution for the original question,
this is a way to solve it with the content instead of an variable name
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.
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
To see the real parameters in ShowParam.bat I use something like this
ShowParam.bat
@echo off
setlocal
set prompt=
@echo on
REM # %* #
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With