批量为文件添加日期时间

批量为文件添加日期时间

此代码从文件夹中读取文件并为所有文件分配相同的日期时间。

代码:

@echo off
set datetime=%date:~4,2%%date:~7,2%%date:~10,4%_%time:~0,2%%time:~3,2%%time:~6,2%
for /f "delims=" %%x in ('dir /b /s D:\v\*.*') do (
  echo %%~dpnx_%datetime%%%~xx>>C:\Users\TechMadmin\Desktop\scripts\a.txt
)
move /y C:\Users\TechMadmin\Desktop\scripts\a.txt C:\Users\TechMadmin\Desktop\scripts\b.txt

输出:

a_08042016_095244.txt 
a_08042016_095244.txt

我的要求是两个文件有不同的日期时间,以便我们可以区分毫秒内的变化。

所需输出:

a_08042016_095244.txt 
a_08042016_095252.txt

答案1

我的要求是两个文件有不同的日期时间

这样我们就可以区分毫秒内的变化。

您可以使用文件创建时间来获取唯一的日期/时间值,因为两个同名文件不太可能具有完全相同的创建时间。

测试.bat:

@echo off
setlocal enabledelayedexpansion
for /f "delims=" %%x in ('dir /a-d /b /s f:\v\*.*') do (
  rem use file creation time to get unique timestamp.
  rem need to double up the \ for the wmic query.
  set _name=%%x
  set _name=!_name:\=\\!
  for /f %%t in ('wmic datafile where name^="!_name!" get creationdate ^| findstr /brc:[0-9]') do (
    set _datetime=%%t
    )
  rem strip last 4 characters as always the same
  echo %%~dpnx_!_datetime:~0,-4!%%~xx>>out.log
)
endlocal

使用示例:

F:\test>dir /a-d /b /s f:\v
f:\v\A\a.txt
f:\v\A\B\a.txt
f:\v\A\C\a.txt
f:\v\A\C\D\a.txt

F:\test>test

F:\test>type out.log
f:\v\A\a_20160804231753.551948.txt
f:\v\A\B\a_20160804231800.344348.txt
f:\v\A\C\a_20160804231803.581548.txt
f:\v\A\C\D\a_20160804231807.072814.txt

您的批处理文件进行了适当修改:

@echo off
setlocal enabledelayedexpansion
for /f "delims=" %%x in ('dir /a-d /b /s d:\v\*.*') do (
  rem use file creation time to get unique timestamp.
  rem need to double up the \ for the wmic query.
  set _name=%%x
  set _name=!_name:\=\\!
  for /f %%t in ('wmic datafile where name^="!_name!" get creationdate ^| findstr /brc:[0-9]') do (
    set _datetime=%%t
    )
  rem strip last 4 characters as always the same
  echo %%~dpnx_!_datetime:~0,-4!%%~xx>>C:\Users\TechMadmin\Desktop\scripts\a.txt
)
move /y C:\Users\TechMadmin\Desktop\scripts\a.txt C:\Users\TechMadmin\Desktop\scripts\b.tx
endlocal

进一步阅读

相关内容