Joshi
Joshi

Reputation: 631

Sending parameters having special characters to another batch file from a batch file

I have the below code:

second.bat file

echo %~1
echo %~2

first.bat file

@ECHO OFF &SETLOCAL
@SETLOCAL EnableExtensions EnableDelayedExpansion

set /p User=Enter Username: 
set /p Password=Enter Password: 

call second.bat %User% %Password%

If user inputs Admin as username and Admin!23 as password the output produced in second.bat echo is as below:

Admin
Admin23

How can I get the special characters as well in the second.bat file like below?

Admin
Admin!23

Upvotes: 2

Views: 3540

Answers (2)

jeb
jeb

Reputation: 82410

It depends of your possiblities.
Are you allowed to change the second.bat file?

Then you should transfer the values by (variable) references instead of values, as CALL doesn't work very well with complex values.

Solution 1:
Then you can change second.bat to

@echo off
echo !user!, !password!

Solution 2:
If you are not allowed to change second.bat and it requires the password as a calling parameter, you could change first.bat to

@ECHO OFF
setlocal EnableExtensions EnableDelayedExpansion

set /p User=Enter Username: 
set /p Password=Enter Password: 

set ^"password=!password:"=""!"
setlocal DisableDelayedExpansion
call second.bat "%%User%%" "%%Password%%"
exit /b

It only fails when quotes in the password are used, then they are doubled.

Solution 3:
Injecting code to second.bat without modifying the file.

Assuming second.bat looks like

@echo off
setlocal EnableDelayedExpansion
set "user=%~1"
set "pwd=%~2"

echo !pwd!

Change first.bat to:

set ^"Inject=." & (set pwd=^!password^!) & rem #"
call second.bat "%%User%%" %%Inject%%

This can handle any password, as the line in second.bat set "pwd=%~2" will be modified on the fly to

set "pwd=." & (set pwd=!password!) & rem #"

Upvotes: 2

geisterfurz007
geisterfurz007

Reputation: 5874

You do not need DelayedExpansion to that point! If you need it after, activate it after! If you echo the last line of your example you will see that the ! should have been missing as well.

As DelayedExpansion uses the exclamation mark as special symbol it gets deleted.

Upvotes: 1

Related Questions