1

I have this issue where I want to re-define a variable with each iteration of a for loop. I cannot figure out why this is not working. I have tried messing with enabledelayedexpansion but have not had success.

echo off
for /f "tokens=1-7 delims=::/ " %%A in ("%DATE% %TIME%") do set capture_time=%%D-%%B-%%C_%%E%%F%%G
for /l %%a in (1,1,3) do (
    echo %capture_time%
    timeout 3 /nobreak
    for /f "tokens=1-7 delims=::/ " %%A in ("%DATE% %TIME%") do set capture_time=%%D-%%B-%%C_%%E%%F%%G
)

My desired output would be something like this:

2015-08-27_132506.50
2015-08-27_132509.50
2015-08-27_132512.50

Where each time the loop is run, the capture_time is updated.

5
  • 2
    You fell into the delayed expansion trap! The variable is set but it is expanded earlier so you don't see the updated value... In this code for instance, there is exactly the same problem... Commented Aug 27, 2015 at 21:54
  • I applied the answer from your first link but it still didn't work. Is it different because I am re-defining the variable "from scratch" each iteration? Commented Aug 27, 2015 at 22:13
  • 1
    The delayed expansion must also be applied to !DATE! and !TIME!... Commented Aug 27, 2015 at 22:15
  • Would you like to make this an official answer? Commented Aug 28, 2015 at 2:34
  • See @Mofi's answer... Commented Aug 28, 2015 at 12:32

1 Answer 1

1

Every environment variable within a block defined with ( and ) and referenced with %Variable Name% is expanded already by command processor on parsing the block. This can be seen on running a batch file from within a command prompt window with using echo on or having @echo off removed or commented out with rem.

The solution is using delayed expansion as demonstrated below.

@echo off
setlocal EnableDelayedExpansion
for /f "tokens=1-7 delims=::/ " %%A in ("%DATE% %TIME%") do set "capture_time=%%D-%%B-%%C_%%E%%F%%G"
for /l %%a in (1,1,3) do (
    echo !capture_time!
    timeout 3 /nobreak
    for /f "tokens=1-7 delims=::/ " %%A in ("!DATE! !TIME!") do set "capture_time=%%D-%%B-%%C_%%E%%F%%G"
)
endlocal

For more details on delayed expansion open a command prompt window, execute there set /? and read all help pages output into the command prompt window carefully. Delayed expansion is explained in help on an example.

Why it is always better to use set "variable=value" instead of set variable=value is explained for example here.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.