-1

Within a FOR loop over all files from a folder, I try to set the file time into a variable, but the variable keeps displaying the same value for all files.

Here is the .bat file content:

@echo off

for /f %%a in ('dir /b .\*.*') do (
    echo a : %%a
    echo ta: %%~ta
    set filetime = %%~ta
    echo filetime: %filetime%
)

Here is the output:

a : File1.txt
ta: 10/03/2023 17:09
filetime: "02/10/2020 17:44"
a : File2.txt
ta: 10/03/2023 17:10
filetime: "02/10/2020 17:44"
a : File3.txt
ta: 10/03/2023 14:02
filetime: "02/10/2020 17:44"
a : test.bat
ta: 10/03/2023 14:35
filetime: "02/10/2020 17:44"

My purpose was to have the actual file time (%%~ta) written in the variable filetime.

  • Your output does not match your code. Batch is sensitive to spaces in an ordinary string `SET` statement. `SET FLAG = N` sets a variable named "FLAG " to a value of " N". Remove the spaces from **both** sides of the `=`. It's normal practice to have a `setlocal` command directly after the initial `@echo off`. This discards any changes made to the environment when the batch ends, so variables established by one batch file do not affect any further batches that may be run in the same session. Your output shows this as none of the timestamps of your files match the value in `filetime`. – Magoo Mar 10 '23 at 16:52
  • As for why it won't vary even when you correct the spaces issue, Beware of the [delayed expansion trap](https://stackoverflow.com/a/30284028/2128947) . The easiest cure would be `call echo %%filetime%%` – Magoo Mar 10 '23 at 16:54

1 Answers1

0

Try removing the spaces around the '='. New line should be: set filetime=%%~ta

https://learn.microsoft.com/en-us/windows-server/administration/windows-commands/set_1