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

6.4k views Asked by At

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.

2

There are 2 answers

0
AudioBubble On BEST ANSWER

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.

1
double-beep On

Here is a slightly faster way in batch file that uses 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.
  • forfiles /M file.ext /C "cmd /C echo @fdate @ftime" runs the command (/C) for the file specified in /M option (file.ext).
  • "cmd /C echo @fdate @ftime" opens a new cmd and carry out the command specified by string and then terminates it.
  • @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.