Can’t concatenate a string inside a batch loop

batchbatch filecmd.execoncatenationstring

I've been struggling with this for a while now, and I can't seem to figure out why.

I have this batch file:

@echo on    
setlocal enabledelayedexpansion

for /F %%x in (FileList.txt) do (
    for /L %%i in (1,1,16) do (
        if %%i LSS 10 (set ctr=0%%i) else (set ctr=%%i)
        echo !ctr!
        set target = \\Server-!ctr! password /user:domain\username
        echo %target%
        echo net use z: %target%
        echo copy %%x "z:%%~pnx" /Y
        echo net use z: /delete
    )
)

My ctr variable is being set appropriately, however, when I try to concatenate it, all I get is: \Server-!ctr! password /user:domain\username. I have tried %!ctr!%, %ctr%, %%ctr, %%ctr%%, all to just have it return the literal characters – not the value. Interestly enough, when I take out the set command, my echo !ctr! does return the value. I have also tried enclosing the set parameters in quotes as well – with the same results, just quotes around it.

What am I missing?

Best Answer

What am I missing

You are not using the set command correctly.

set target = \\Server-!ctr! password /user:domain\username

This creates a variable called "target " (note the extra space after the name).

In addition the right hand side of the expression contains spaces, so you also need some quotes.

Any extra spaces around either the variable name or the string, will not be ignored, SET is not forgiving of extra spaces like many other scripting languages.

Source set

Try the following replacement:

set target="\\Server-!ctr! password /user:domain\username"

You are also not using (understanding) delayed expansion correctly.

echo %target%
echo net use z: %target%

Delayed Expansion will cause variables to be expanded at execution time rather than at parse time.

Source enabledelayedexpansion

This should be:

echo !target!
echo net use z: !target!

Further Reading

Related Question