0

I have two files.

values.properties

user=username
password=Password1234!

mybatch.bat

SETLOCAL EnableDelayedExpansion
For /F "tokens=1,2 delims==" %%A IN (path/values.properties) DO (
    IF "%%A"=="user" set user=%%B
    IF "%%A"=="password" set password=%%B
    )

In the batch file, password's value is:

Password1234

So basically, the "!" disappear. I want to make "password" store any value, no matter what special characters will contain. How can I do this? I tried to escape the "!" be adding "password=^^%%B". Did not work.

Thank you.

aschipfl
  • 33,626
  • 12
  • 54
  • 99
bogdanov
  • 113
  • 3
  • 14
  • 1
    Disable delayed expansion and you'll see it works; the problem is that `%%A` is expanded before delayed expansion occurs, which consumes the `!`... – aschipfl Dec 11 '18 at 14:11
  • I can't believe it! It worked. I still don't know why I've added the "EnableDelayedExpansion". I am working for some time to this script and it was needed somewhere. Thank you very much. Can you add your comment as an answer so I can approve it? You rock! – bogdanov Dec 11 '18 at 14:15

2 Answers2

3

Excuse me. I can't resist the temptation to post this answer...

Supose you have a numeric variable, that may have the values 10, 25 and 50, and you want to add it to a total variable. You may do it this way:

if %num% equ 10 set /A total+=10
if %num% equ 25 set /A total+=25
if %num% equ 50 set /A total+=50

... or you may do it this way:

set /A total+=num

Which one would you prefer?


The problem with your code is that you Enable Delayed Expansion at the moment the assignment is done. Just remove it and, if you need it, just enable it later:

SETLOCAL
For /F "delims=" %%A IN (path/values.properties) DO set "%%A"

SETLOCAL EnableDelayedExpansion
echo Password=!password!

The other changes in the code are explained in the first part of this answer. The quotes around %%A are used to protect other special characters, like & or >.

Aacini
  • 65,180
  • 12
  • 72
  • 108
  • Thank you very much for the information! As you probably found out, I just started to learn how to use batch files. I was trying to add comments in the .property file so that's why I wanted to get rid of all the special characters(I removed the comments anyway). I couldn't find a better way to assign the values from my property file. – bogdanov Dec 11 '18 at 14:48
1

The issue is that you are expandion a for variable reference %%A while having delayed expansion enabled, which consumes the exclamation mark.

Therefore simply disable delayed expansion and your code works.

Let me recommend to use the quoted set syntax set "user=%%B" in order to avoid trouble with special characters.

aschipfl
  • 33,626
  • 12
  • 54
  • 99