I have a long test.properties file that contains the following at the very top:
property1=cheese
property2=apple
property3=bread
# many more properties
I can read those properties from the command line by changing the working directory to the one containing test.properties and running the following command:
> FOR /F "tokens=1,2 delims==" %A IN (test.properties) DO
IF "%A"=="property1" SET firstitem=%B
> FOR /F "tokens=1,2 delims==" %A IN (test.properties) DO
IF "%A"=="property2" SET seconditem=%B
> echo %firstitem%
cheese
> echo %seconditem%
apple
However, when I try to put this code in a batch file stored in the same directory, it fails and I cannot work out why:
FOR /F "tokens=1,2 delims==" %A IN ("%~dp0\test.properties") DO
(IF "%A"=="property1" SET firstitem=%B)
FOR /F "tokens=1,2 delims==" %A IN ("%~dp0\test.properties") DO
(IF "%A"=="property2" SET seconditem=%B)
Running the batch file from the command line gives me this:
> "C:\folder\testbatch.bat"
~dp0\test.properties") DO IF "B was unexpected at this time.
What can I do to read the properties using the batch file, so that they are stored in variables that can be used in the rest of the script?
EDIT: Problem solved; working code below.
FOR /F "usebackq tokens=1,2 delims==" %%A IN ("%~dp0\test.properties") DO
(IF "%%A"=="property1" SET firstitem=%%B)
FOR /F "usebackq tokens=1,2 delims==" %%A IN ("%~dp0\test.properties") DO
(IF "%%A"=="property2" SET seconditem=%%B)
There's two problems here:
usebackq
modifier for a more general solution. But since you're talking about "batch file stored in the same directory", you might as well drop the path prefix %~dp0
altogether.Corrected version:
@ECHO OFF
FOR /F "tokens=1,2 delims==" %%A IN (test.properties) DO (
IF "%%A"=="property1" SET firstitem=%%B
)
FOR /F "tokens=1,2 delims==" %%A IN (test.properties) DO (
IF "%%A"=="property2" SET seconditem=%%B
)
ECHO %firstitem%
ECHO %seconditem%
Returns:
cheese
apple