Tuesday, May 13, 2008

Add Date and Time Stamps to Your Batch Files

Ever want to setup a windows batch file to output a date or time without using vbscript? My specific reason for researching this function was to dynamically generate a new log file each time my script was run. The following code will set the date and time into variables names %cdate% and %ctime% and then generate a text file named backup-DATE-TIME.txt (obviously replacing DATE and TIME with the current date and time).
@echo off
REM This section sets the date variables
FOR /F "tokens=1-4 delims=/- " %%a in ('date/T') do set CDATE=%%b%%c%%d
REM The following formats the date variable to MMDDYY
SET CDATE=%CDATE:~0,4%%CDATE:~-2%
FOR /F "tokens=1-4 delims=:., " %%a in ("%TIME%") do set CTIME=%%a%%b%%c
echo.
echo. > c:\logs\backup-%cdate%-%ctime%.txt
echo.

This script can be inserted into almost any script fairly easy and you can utilize the date and time variables anywhere in the script.

References:

Batchfiles FAQ

No comments: