Jorden Krowen
Jorden Krowen

Reputation: 53

Why is the current time not updated in a FOR loop?

I'm trying to print each file name with a time stamp in batch file. This is my batch script:

@echo off
setlocal enabledelayedexpansion

for /R "C:\Users\user\Desktop\BdayClip" %%B in (*.*) do (
    echo "%time::=-%%%~xG"
    choice /d y /t 1 > nul
)

I'm getting all the files name with the same time stamp and a delay of 1 second as excepted. But the time stamp is not changing!

Someone online said that adding the enabledelayedexapnsion works for him, but it didn't change anything on my script.

The output as following:

6-32-12.34.png
6-32-12.34.png
6-32-12.34.png

Why is always the same time output on running this FOR loop?

Upvotes: 5

Views: 2845

Answers (1)

Mofi
Mofi

Reputation: 49086

You ran into delayed expansion trap. set /? explains delayed expansion on an IF and a FOR example. You have enabled delayed expansion, but do not make use of it because of referencing dynamic environment variable TIME with percent signs which means with expansion in command block during preprocessing phase before executing command FOR.

@echo off
setlocal EnableExtensions EnableDelayedExpansion
for /R "%USERPROFILE%\Desktop\BdayClip" %%B in (*) do (
    echo !TIME::=-!%%~xB
    %SystemRoot%\System32\choice.exe /d y /t 1 >nul
)
endlocal

Dynamic environment variable TIME is now referenced with exclamation marks which means with usage of delayed expansion.

For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.

  • choice /?
  • echo /?
  • endlocal /?
  • for /?
  • set /?
  • setlocal /?

Upvotes: 4

Related Questions