Printing current date and time in DOS script

前端 未结 1 545
清歌不尽
清歌不尽 2021-02-04 04:52

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

1条回答
  •  孤街浪徒
    2021-02-04 05:56

    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.

    0 讨论(0)
提交回复
热议问题