Printing current date and time in DOS script

Rayne picture Rayne · Sep 21, 2012 · Viewed 80.8k times · Source

I have a script that prints the date and time followed by a string in a log.

echo %DATE%_%TIME% Processing %%f >> process.log

The problem is that the date and time is always the date and time when the script is started. I've been running the script overnight, and still has the same date and time. Is there a way to update them so it shows the current date and time when the string is printed to the log file?

Answer

dbenham picture dbenham · Sep 21, 2012

The fact that you have %%f indicates your echo command is in a FOR loop. The entire FOR loop is parsed at once, and %DATE% is expanded at parse time. The command is not re-parsed for each iteration, so that is why you get the same value for each iteration. You get the value that existed before the FOR statement is executed!

The solution is delayed expansion. Put setlocal enableDelayedExpansion near the top of your script. Then use !DATE!_!TIME! instead of %DATE%_%TIME%. Delayed expansion means the expansion occurs when the statement is executed, not when it is parsed. There is a good explanation in the HELP system. Type HELP SET or SET /? from a command prompt and look for the section that deals with delayed expansion.