Escape user input in a Windows batch file

I have a Windows batch file that accepts a password as user input:

SET /P PASSWORD=Password:

This password can be characters you want to perform, for example !. Then the variable PASSWORDis passed to other commands usingCALL

CALL Foo.Bat %PASSWORD%

How can I guarantee that special characters will be escaped and passed correctly as a parameter? For example, if the user types !%"£$", I want to %1be !%"£$"in Foo.bat.

+5
source share
1 answer

, .
: , .

.

call foo.bat password

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

Setlocal EnableDelayedExpansion
Echo !password!

EDIT: ,

CALL .
- 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

ShowParam.bat, -
ShowParam.bat

@echo off
setlocal
set prompt=
@echo on
REM # %* #
+2

All Articles