MS Windows – Create timestamp copy of original file ( using batch file )


There is a batch file that I have that fails occasionally.

And, yes it creates a log file.

But, unfortunately by the time that I go look, it has re-attempted and worked well.

And, so I am losing the error message.


Clone File

Let us clone the file and name the new file based on our current timestamp.


  1. Building Block
    • _getTimeStamp.cmd
    • _fileBackup.cmd
  2. Use case
    • fileBackupInvoke.cmd

Building Block


@echo off
@setlocal enableextensions enabledelayedexpansion
rem Creating a file name as a timestamp in a batch job
rem BeConcise
rem copy "{path}\example.txt" "{path}\_%date:~10,4%%date:~4,2%%date:~7,2%_%time:~0,2%%time:~3,2%%time:~6,2%.txt"
rem set "_timestampSaved=%date:~10,4%%date:~4,2%%date:~7,2%_%time:~0,2%%time:~3,2%%time:~6,2%"
rem Need leading zero for batch script using %time% variable
:prepare time stamp 
set year=%date:~10,4%
set month=%date:~4,2%
set day=%date:~7,2%
set hour=%time:~0,2%
:replace leading space with 0 for hours < 10
if "%hour:~0,1%" == " "  set hour=0%hour:~1,1%
set minute=%time:~3,2%
set second=%time:~6,2%
set _timeStamp=%year%%month%%day%_%hour%%minute%%second%
    rem SET _timestamp=%_timestamp%
    SET _timestampSaved=%_timestamp%




REM Reset local variables
set _timestampSaved=

REM Validate arguments passed in through command line
REM Argument List
REM 	1) File Name 
REM 	2) File Extension
IF %1.==. GOTO No1
IF %2.==. GOTO No2
call _getTimeStamp.cmd

rem set "_DATEANDTIME=%_timestampSaved%"
rem echo "TimestampSave is %_DATEANDTIME%"

REM The originating file is filename and file ext
set "_fileSource=%1%2"

REM The destination file is filename, timestamp, and file ext
set "_fileDestination=%1_%_timestampSaved%%2"

REM Display file name source & destination
echo file Source is %_fileSource%
echo file Destination is %_fileDestination%

REM make backup of file ( file Source -> file destination )
if exist %_fileSource% echo "f" | xcopy %_fileSource% %_fileDestination% /D

REM Go to end

    ECHO Please pass in file name as param 1
	GOTO End1

    ECHO Please pass in file extension as param 2
	GOTO End1


Use Case



@echo off

if not exist log mkdir log

set "_fileSource=log\refreshData"
set "_fileExtension=.log"

call _fileBackup.cmd %_fileSource% %_fileExtension%



Source Code Control





As always, nothing here.

Unfortunately logic for getting timestamp is often a hit and miss.

Especially when one considers zero (0) offset that is often amiss.




Leave a Reply

Please log in using one of these methods to post your comment: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s