4

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?

Mofi
  • 46,139
  • 17
  • 80
  • 143
  • See `set /?` for an explanation of Expansion. – ACatInLove Jan 07 '18 at 09:30
  • Looks like your trying to get current time and extension of each file. The timestamp of a file in my understanding, is the time stamped on the filename i.e `echo %%~tB %%~nxB`. That uses the `t` modifier and the `nx` modifiers to get timestamp and filename with extension. – michael_heath Jan 07 '18 at 10:37
  • 2
    Possible duplicate of [Batch file variables initialized in a for loop](https://stackoverflow.com/questions/691047/batch-file-variables-initialized-in-a-for-loop). You may want to learn to search before asking questions, just a friendly piece of advice. This question, or slight variations on it, have been asked many times before. – paxdiablo Jan 07 '18 at 12:04

1 Answers1

3

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 /?
Mofi
  • 46,139
  • 17
  • 80
  • 143