Logs Named By Current DateTime


I have a scheduled task and I’d like to save logs from the output. After some quick batch file work, I came up with this.

@echo off
setlocal

for /f "tokens=2" %%A in (‘date /t’) DO @(set MyDate=%%A)
set MyDate=%MyDate:/=-%

set MyTime=%TIME::=-%
set MyTime=%MyTime:.=-%
set MyFilename=%MyDate%_%MyTime%.log

echo Writing output to %MyFilename%
mytask.exe > %MyFilename%

endlocal

I end up with filenames like 10-02-2009_14-34-56-00.log which gets the point across. Do you have a better way to accomplish this?


Comments (1)

  1. RLapinski says:

    You could also use undocumented environment variables: %date% and %time% and some string extraction techniques. Those variables are updated by system in real-time so all you need it's just to use them. Because of this you may want also to use additional variable to assign your filename string due to the they may change during script executions (if you use them multiple times).

    And it also depends on regional settings (in Your example also).

    Here's simple example (I'm using it in my scripts):

    (for English US) echo %date:~10,4%%date:~4,2%%date:~7,2%_%time:~0,2%%time:~3,2%

    Example output: 20101013_1734

    (for English UK) echo %date:~0,4%%date:~5,2%%date:~8,2%_%time:~0,2%%time:~3,2%

    Example output: 20101013_1734

    Greetings,

    Robert