Rename a file by appending the current date and time to the existing filename:
@ECHO off
SETLOCAL
IF [%1] NEQ [] goto s_start
:: Author - Simon Sheppard, Aug 2009
:: Tested for Windows XP, Windows 2008
Echo STAMP.cmd
Echo Rename a file with the DATE/Time
Echo.
Echo Syntax
Echo STAMP TestFile.txt
Echo.
Echo STAMP "Test File.txt"
Echo.
Echo STAMP "c:\docs\Test File.txt"
Echo.
Echo Will rename the file in the format "Test File-2009-12-30@16-55.txt"
Echo.
Echo In a batch file use CALL STAMP ...
GOTO :eof
:s_start
Set _file=%~n1%
Set _pathname=%~f1%
Set _ext=%~x1%
::Get the date
For /f "tokens=1-4 delims=/-. " %%G in ('Date /t') Do (Call :s_fixdate %%G %%H %%I %%J)
Goto :s_time
:s_fixdate
if "%1:~0,1%" GTR "9" Shift
For /f "skip=1 tokens=2-4 delims=(-)" %%G in ('Echo.^|Date') Do (
Set %%G=%1&Set %%H=%2&Set %%I=%3)
goto :eof
:s_time
:: Get the time
For /f "tokens=1-3 delims=1234567890 " %%a in ("%time%") Do Set "delims=%%a%%b%%c"
For /f "tokens=1-4 delims=%delims%" %%G in ("%time%") Do (
Set _hh=%%G
Set _min=%%H
Set _ss=%%I
Set _ms=%%J
)
:: Strip any leading spaces
Set _hh=%_hh: =%
:: Ensure the hours have a leading zero
if 1%_hh% LSS 20 Set _hh=0%_hh%
Echo Year-Month-Day@Hour-Min-Sec
Echo %yy%-%mm%-%dd% @ %_hh%-%_min%-%_ss%
REN "%_pathname%" "%_file%-%yy%-%mm%-%dd%@%_hh%-%_min%-%_ss%%_ext%"
This is based on the GetDate and GetTime scripts, the last line does the file rename.
Example
c:\> stampme "sample file.txt"
An alternative 'quick and dirty' way to do the same thing in one line is shown below, this does work but is less robust as the results will vary according to regional/control panel settings.
c:\> REN "sample file.txt" "* %Date:/= % %Time::=.%.*"
"The time you enjoy wasting is not wasted time” - Bertrand Russell
Related
DelOlder.cmd - Delete files more than n days old
Stampme.ps1 - Powershell version