在DOS脚本中打印当前日期和时间

在DOS脚本中打印当前日期和时间

本文介绍了在DOS脚本中打印当前日期和时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个脚本,可在日志中打印日期和时间,后跟字符串。

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?

推荐答案

您具有 %% f 的事实表明您的echo命令处于FOR循环中。整个FOR循环被一次解析,并且%DATE%在解析时被扩展。不会为每个迭代重新解析该命令,因此这就是为什么您为每个迭代获得相同值的原因。您将获得执行FOR语句之前存在的值!

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!

解决方案是延迟扩展。将 setlocal enableDelayedExpansion 放在脚本顶部附近。然后使用!DATE!_!TIME!代替%DATE%_%TIME%。延迟扩展意味着扩展在执行语句时发生,而不是在分析语句时发生。 HELP系统中有很好的解释。在命令提示符下键入 HELP SET SET /?并查找处理延迟扩展的部分。

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.

这篇关于在DOS脚本中打印当前日期和时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-26 10:29