Print current date and time in DOS script

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

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

The problem is that the date and time are always the date and time the script started. I run the script in one night and still have the same time and date. Is there a way to update them so that they display the current date and time when the line is printed in the log file?

+12
date time dos
Sep 21
source share
1 answer

The fact that you have %%f indicates that your echo command is in a FOR loop. The entire FOR loop is parsed immediately, and %DATE% expands during parsing. The command is not re-processed for each iteration, so you get the same value for each iteration. You get the value that existed before executing the FOR!

The solution is slow expansion. Put setlocal enableDelayedExpansion at the top of your script. Then use !DATE!_!TIME! instead of %DATE%_%TIME% . Deferred extension means that the extension occurs when the statement is executed, and not when it is parsed. There is a good explanation in the HELP system. Enter HELP SET or SET /? from the command line and find the section that deals with extension delay.

+32
Sep 21 '12 at 12:29
source share
— -



All Articles