mathB
mathB

Reputation: 634

extract file timestamp of multiple files batch

My task is to extract the timestamp of all the files that are stored in a txt file (with full path). I'm using for loop to do this, but I always get incorrect date and time. Here's what I have written:

@echo off
for /f %%a in (D:\Balaji\filepath\output3.txt) do call :Sub2 %%a
goto :eof

:Sub2
echo.
if exist %1 (
    echo File %1 has arrived update the DB.
    FOR %%f IN (%1) DO (
        SET filedatetime=%%~tf
    )
    echo Datetime of %1 is: %filedatetime%
)

The result I get is the modified date/time of the second file in the list rather than the first one. Where am I going wrong?

Result:

File D:\folder\test.txt has arrived update the DB.
Datetime of D:\folder\test.txt is:

File D:\folder\filenames.sql has arrived update the DB.
Datetime of D:\folder\filenames.sql is: 10/19/2016 03:53 PM

File D:\folder\test1.txt has arrived update the DB.
Datetime of D:\folder\test1.txt is: 12/22/2016 02:20 PM

File D:\folder\file.csv has arrived update the DB.
Datetime of D:\folder\file.csv is: 12/22/2016 04:50 PM

Upvotes: 0

Views: 613

Answers (2)

aschipfl
aschipfl

Reputation: 34909

  1. Add option "delims=" to for /F to not split paths containing SPACE characters.
  2. Use "%~1" rather than %1 to avoid trouble with special characters like e. g. ^ & ( ).
  3. In your code, either use delayed expansion for variable filedatetime, or reverse the if query to if not exist "%~1" goto :EOF to avoid filedatetime to be changed and read in the same parenthesised block of code.
    Anyway, there is actually no need for the for loop as the ~t modifier is also supported by argument references like %1.

So here is the fixed code:

@echo off
for /F "usebackq delims=" %%A in ("D:\Balaji\filepath\output3.txt") do call :Sub2 "%%A"
goto :EOF

:Sub2
echo/
if not exist "%~1" goto :EOF
echo File "%~1" has arrived update the DB.
echo Datetime of "%~1" is: %~t1

Actually, you do not even need the sub-routine for this:

@echo off
for /F "usebackq delims=" %%A in ("D:\Balaji\filepath\output3.txt") do (
    echo/
    if exist "%%~A" (
        echo File "%%~A" has arrived update the DB.
        echo Datetime of "%%~A" is: %%~tA
    )
)

Upvotes: 4

Magoo
Magoo

Reputation: 80023

:Sub2
echo.
if NOT exist %1 GOTO :EOF
echo File %1 has arrived update the DB.
FOR %%f IN (%1) DO SET filedatetime=%%~tf
echo Datetime of %1 is: %filedatetime%

or

:Sub2
echo.
if NOT exist %1 GOTO :EOF
echo File %1 has arrived update the DB.
FOR %%f IN (%1) DO echo Datetime of %1 is: %%~tf

The problem is delayedexpansion - many SO items on this. %var% is replaced in a block (parenthesised sequence of lines) with its value at the time the outermost block was encountered. There are ways around - read more SO items about delayed expansion

Upvotes: 1

Related Questions