How to use delayed expansion on a variable like %%a or %1?

Viewed 159

I'm trying to make a batch file I call from another batch file, but the variables don't work, all the results are "a", while the expected result would be option1=a, option2=b, etc.

Here's the code to demonstrate the issue:

call temp.bat a b c d e f g h i j k l m n o p q r s t e u v w x y z
pause
exit

and for temp.bat:

set Number=0
for %%a in (%*) do set /a Number+=1

for /l %%a in (1,1,%Number%) do (
    set option%%a=%1
    shift
)
exit /b

I've tried !%1! with empty results; %%1% gave "%1" as the result; %1% had the same result as just using %1

2 Answers

You could do this with one FOR command which would be much more efficient.

Using the CALL Method

@echo off

set Number=0
for %%a in (%*) do (
    set /a Number+=1
    call set "option%%Number%%=%%a"
)

Using Delayed Expansion

@echo off
setlocal enabledelayedexpansion
set Number=0
for %%a in (%*) do (
    set /a Number+=1
    set "option!Number!=%%a"
)
Related