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?
Bookmark this question. Show activity on this post. In Linux I do date +"%Y%m%d%H%M%S" to print a date and time label.
On a Microsoft Windows system, you can obtain the current date using the date /t command (the /t option prevents the command from prompting for a change to the the date) or by using echo %date% to display the contents of the date environment variable.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With