January 31, 2019

Batch file script - Get date-time value in string variable

Batch file is an important tool to automate different tasks, e.g. Copying files/folders, Archiving, Taking backups, Running builds and lot more... Often times we need to create date-time stamp in a string variable for different purposes. For example, I want to write a batch script which will copy a file to a destination folder, but before copying in destination folder I want it to append the date time stamp in target file name. In this post we will see how to pepare date time stamp as string variable in batch file. Here is the script.


::----------------------------------------------------------------------------------------------
::prepare date-string
::----------------------------------------------------------------------------------------------

:: Get day from current date, in variable name 'day'
SET day=%date:~7,2%

:: Get month from current date, in variable name 'month'
SET month=%date:~4,2%

:: Get year from current date, in variable name 'year'
SET year=%date:~10,4%

:: Set year+month+date for date-string, in variable name 'myDateFormat' 
SET myDateFormat=%day%-%month%-%year%

:: Trim myDateFormat to remove white spaces
SET myDateFormat=%myDateFormat: =%

::----------------------------------------------------------------------------------------------
::prepare time-string
::----------------------------------------------------------------------------------------------

:: Get hour from current time, in variable name 'hour'
SET hour=%time:~0,2%

:: Get minute from current time, in variable name 'minute'
SET minute=%time:~3,2%

:: Get second from current time, in variable name 'sec'
SET sec=%time:~6,2% 

:: Set hour+minute+second for time-string, in variable name 'myTimeFormat'
SET myTimeFormat=%hour%-%minute%-%sec%

:: Trim myTimeFormat to remove white spaces
SET myTimeFormat=%myTimeFormat: =%

::----------------------------------------------------------------------------------------------
::set targetFileName with string literal, and also append the date and time strings at the end.
::----------------------------------------------------------------------------------------------

SET targetFileName=CRM System Log-%myDateFormat%-%myTimeFormat%.txt

::copy file, using the variable targetFileName 
copy "C:\Test\CRM System Log.txt" "C:\Test\Destination\%targetFileName%"

I hope this helps some of you who get stuck with a similar problem.

No comments:

Post a Comment