提取多个文件批处理的文件时间戳

时间:2016-12-22 13:08:09

标签: batch-file cmd timestamp

我的任务是提取存储在txt文件中的所有文件的时间戳(带有完整路径)。我使用for循环来做这件事,但我总是得到错误的日期和时间。这是我写的:

@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%
)

我得到的结果是列表中第二个文件的修改日期/时间而不是第一个文件。我哪里错了?

结果:

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

2 个答案:

答案 0 :(得分:4)

  1. 将选项"delims="添加到for /F,以便不拆分包含 SPACE 字符的路径。
  2. 使用"%~1"而不是%1来避免像e这样的特殊字符出现问题。 G。 ^ & ( )
  3. 在您的代码中,使用delayed expansion表示变量filedatetime,或将if查询反转为if not exist "%~1" goto :EOF,以避免filedatetime被更改并读入相同的括号代码块。
    无论如何,实际上不需要for循环,因为~t等参数引用也支持%1修饰符。
  4. 所以这是固定代码:

    @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
    

    实际上,你甚至不需要这个子程序:

    @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
        )
    )
    

答案 1 :(得分:1)

: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%

: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

问题是delayedexpansion - 很多SO项目。在遇到最外层块时,%var%的块(带括号的行序列)中被替换。有办法解决 - 阅读更多有关delayed expansion

的SO项目