Monday, February 23, 2009

Date and Time in Batch for Log File Name

Setting up a batch file and configuring a command line utility and identifying, for Windows servers, a process to execute the application and have unique log files recorded.


REM take the system date and convert it to YYYYMMDD format
set MyDate=%date:~10,4%%date:~7,2%%date:~4,2%

REM take the system time and convert to an HHMM format
set MyTime=%time:~0,2%%time:~3,2%
REM if earlier than 10 oclock then convert leading space to a 0:
REM note it is %MyTime:<space>=0%
set MyTime=%MyTime: =0%
REM if its after 10 then this has no effect so theres no need to test for the time

REM Next set the %logfile% configuration for daily retention

set logfile=%MyDate%%MyTime%.log

REM use the %logfile% variable in the command line e.g.
c:\bin\spwakeup.exe -log:c:\logs\spwakeup\%logfile%


Of course, the date and time editing could be to any sequence you prefer.

The idea is to break the system date into little strings and manipulate them to your needs.

set MyDate=%date:~10,4%%date:~7,2%%date:~4,2%

is really saying to the system

get the system date "%date"

do something with it ":"
edit it down "~"
from character position "10"
for a length of ",4" (the year including century YYYY format)
end this variable component "%"

repeat for the characters at position 7 for a length of 2 (the month in MM format)
and again for the day at position 4 for a length of 2 (the day in DD format)

and because all three instructions are strung together then the result is pushed into the variable named MyDate (without the %'s when setting, but with %MyDate% when you want to use the value) the output will be the date in YYYYMMDD format.

Likewise with the Time value and then setting the logfile name.



No comments: