Believe me, I've searched around but I haven't had any joy with this seemingly innocuous problem.
NOTE: There are some posts and answers on SO surrounding issues with batch variables in for
loops; it's likely that many will not realize that if
blocks impose the same complications regarding expansion.
I'm far from a batch file aficionado, so I'm likely missing something basic, but when I run the following script:
set testVar1=Initial Value 1
echo testVar1 = %testVar1%
if 1==1 (
echo In If Block
echo testVar1 = %testVar1%
set testVar1=In If Block
echo testVar1 = %testVar1%
set testVar2=Initial Value 2
echo testVar2 = %testVar2%
)
echo Out of If Block
echo testVar1 = %testVar1%
echo testVar2 = %testVar2%
I get:
testVar1 = Initial Value 1
In If Block
testVar1 = Initial Value 1
testVar1 = Initial Value 1
testVar2 =
Out of If Block
testVar1 = In If Block
testVar2 = Initial Value 2
Whereas what I would expect to see is:
testVar1 = Initial Value 1
In If Block
testVar1 = Initial Value 1
testVar1 = In If Block
testVar2 = Initial Value 2
Out of If Block
testVar1 = In If Block
testVar2 = Initial Value 2
Within the if
block, I change the value of testVar1
but when I echo it, it has the original value. Similarly, I create a new testVar2
variable within the if
block but when I echo it, it has a null value.
Yet once I exit the if
block, the values set within it are correct when echoed.
I've been very careful with spaces in declarations, as mentioned elsewhere, and I've tried several variations but the above is the most basic test I can devise to illustrate the issue.
As I said, no doubt I'm missing something obvious but I don't know what it is.
I've also tried adding setlocal EnableDelayedExpansion
as I've seen mention of this, but it made no difference.