0
votes

I have a simple ini file... really just a key=value file that I want to use to set as variables for my script.

My ini file:

DATABASE=snoopy

My Batch file code

@echo off
SET DATABASE=woodstock

FOR /f "tokens=1,2 delims==" %%a in ('C:\mycfg.ini') do (
    echo a=%%a
    echo b=%%b
    pause
    SET %%a=%%b
    ECHO DATABASE=%DATABASE%
)

The echo a and b are correct, it shows

a=DATABASE
b=snoopy

But at the end when I echo %DATABASE% after calling the SET %%a=%%b It still shows

DATABASE=woodstock

If I use delayed expansion, it works but only locally. I need it to overwrite the global so I don't see why this shouldn't work.

2
Would you explain what you mean by local versus global? Is local the current CMD window and global the set of environment variables that are set when you open a new CMD window from the Start Menu (e.g., all future CMD windows)? BTW - You won't be able to modify other already open CMD windows. - James L.
I mean using SetLocal/EndLocal.. Actually thinking about it, I am using SetLocal before the for loop.. maybe I should be using it at the top of the file. I'll try that - Dss
When you enabled delayed expansion, did you change your echo to use the delayed-expansion operator? ECHO DATABASE=!DATABASE! - indiv

2 Answers

0
votes

Well, no need to do anything to make it work.

It works.

Your problem is that when the for block (all the lines in parenthesis in your code) are read, variables are replaced with their values, so the line echo %DATABASE% is converted in echo woodstock. BUT the variable hold the correct value, changed inside the for loop. Try to place the echo outside of the for and see what the value is.

Delayed expansion is needed when a variable is changed inside a block and it is necesary to access the changed value inside the same block.

0
votes

Ok I got it now.. Had to enable delayed expansion at the top of the file rather than just on the subroutine call. Then set the %%a and %%b to delayed variables and set them equal to eachother and that worked. Final code:

@echo off
SetLocal EnableDelayedExpansion

SET DATABASE=woodstock

FOR /f "tokens=1,2 delims==" %%a in ('C:\mycfg.ini') do (
   set tmpA=%%a
   set tmpB=%%b
   SET !tmpA!=!tmpB!
)
ECHO DATABASE=%DATABASE%

And that changes it to "snoopy"

Thanks all!