简体   繁体   中英

Append to a filename last modified date and time with a batch file

I am trying to copy all *.csv files from a folder to another folder, but while copying I need to add modified date and time of file to filename. For example, if filename is Test.csv and it was modified on 11/21/2018 15:01:10 output should be Test11-21-201815_01-10.csv . I found a script to add current timestamp to it, but I need to add modified date of file. You can see it below:

@echo off
set Source=C:\csvtest
set Target=C:\csvtest\csvtest\Archive
FOR /f "tokens=1-8 delims=/.:- " %%A in ("%date%%time%") DO (
SET Month=%%B
SET Day=%%C
SET Year=%%D
SET Hours=%%E
SET Minutes=%%F
SET Seconds=%%G
SET All=%%B-%%C-%%D_%%E-%%F-%%G
)

FOR %%i IN ("%Source%\*.csv") DO (
COPY "%%i" "%Target%\%%~Ni %All%.csv")

Thanks in advance for your help.

There are some examples here on SO for appending a date,
but I'd use PowerShell as a tool to accomplish this (wrapped in batch).

:: Q:\Test\2018\11\23\SO_53450598.cmd
@echo off
set "Source=C:\test"
set "Target=C:\test\Archive"
PowerShell -Nop -C "Get-ChildItem '%Source%\*.csv'|Copy-Item -Destination {'%Target%\{0} {1:MM-dd-yyyy_HH-mm-ss}.csv' -f $_.BaseName,$_.LastWriteTime} -WhatIf"

If the output looks OK, remove the -WhatIf at the end.

@LotPings way lasts a lot of time if PowerShell isn't loaded.

So, I will provide a much faster and more understandable way in batch-file which needs delayedexpansion :

@echo off
setlocal enabledelayedexpansion
for /f "tokens=1-2" %%a IN ('forfiles /M file.ext /C "cmd /C echo @fdate @ftime"') do (
 set line1=%%a
 set line2=%%b
 set line1r=!line1:/=-!
 set line2r=!line2::=-!
 rename "file.ext" "file!line1r!!line2r!.ext"
)
rem NOTE: Date format is DD-MM-YYYY. Time format is HH-MM-SS.

Let's break it down:

for /f ... is well known to you I believe.

Command forfiles /M file.ext /C "cmd /C echo @fdate @ftime" means to run command ( /C ) for file specified in /M option ( file.ext ). "cmd /C echo @fdate @ftime" means to open a new cmd and carry out the command specified by string and then terminate. @fdate is the last modified date of the file and @ftime is the last modified time of the file.

We set variables line1 and line2 for each of @fdate and @ftime and then we make some format changes to them.

Finally, we rename file.ext to fileDD-MM-YYYYHH-MM-SS.ext .

For more information type for /? & forfiles /? for /? & forfiles /? in a fresh cmd.

Hope this helps you, as it is faster.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM