正确地为批处理脚本创建的日志文件添加时间戳 [英] Properly timestamp a log file created by batch script
问题描述
我正在尝试使用在批处理文件中发生的事件的时间戳创建日志文件.
I am trying to create a log file with timestamps of events that are taking place in a batch file.
从下面的代码中可以看到,在编写批处理文件时,我不是专家.尽管该技术非常差,但该过程仍应按预期进行.为了防止批处理文件被删除,我将其设置为只读.我将设法弄清楚如何在某些时候排除批处理文件.现在那还不那么重要.
As you can see from the code below, I am not an expert when it comes to writing a batch file. The process works as it should, although the technique is very poor. In order to keep the batch file from deleting itself, I set it to read-only. I'll get around to figuring out how to exclude the batch file at some point. Right now that isn't as important.
@echo off
echo Compressing Files...
echo Compression Batch File STARTED: %date% %time% >> c:\temp\backup-compress.log
echo --------------------------------------------- >> c:\temp\backup-compress.log
for %%X in (*) do (
"c:\Program Files\7-Zip\7z.exe" a -tgzip "%%X.gz" "%%X"
echo %%X Compressed: %date% %time:~-11,8% >> c:\temp\backup-compress.log
echo Deleting: %%X
del "%%X"
echo %%X Deleted: %date% %time:~-11,8% >> c:\temp\backup-compress.log
)
echo Moving compressed copies to Compressed Backups folder...
move *.gz "Compressed Backups\" > NUL
echo --------------------------------------------- >> c:\temp\backup-compress.log
echo Compression Batch File FINSHED: %date% %time% >> c:\temp\backup-compress.log
echo Compression completed successfully...
echo
生成的日志文件完全符合我的期望,但是,时间戳记和日期在整个日志中保持不变.我不会看到批处理文件中发生事件时的更新时间戳,而只能看到启动批处理文件的时间和日期,而不是每个%time%和%date%实例.
The resulting log file looks exactly how I want it to, however, the time stamp and date remain constant throughout the log. Rather than an updated time stamp as events occur in the batch file, I only see the time and date that the batch file was started in place of every %time% and %date% instance.
如何解决此问题,并为正在创建的日志文件查看正确的时间和日期戳?
PS:请原谅我的这篇文章的篇幅以及可能要解决的简单问题.另外,如果标签不太正确,对不起,这是我第一次实际发布问题,尽管该网站一直以来都是解答问题的理想资源.
PS: Forgive me for the length of this post and what is likely a simple problem to solve. Also, if the tags are not quite right, I apologize, this is my first time actually posting a question, although the site has always been a great resource for answers.
推荐答案
这是因为cmd
在不是直接在执行之前进行解析的语句时会扩展变量.在这种情况下,语句是完整的for
,包括其后的块.因此,for
循环中保留的只是文字字符串,没有变量.
This is because cmd
expands variables when a statement is parsed not directly prior to execution. A statement in this case is the complete for
including the block after it. So all that remains within the for
loop are literal strings, no variables.
您可以使用延迟扩展来更正此问题.在批处理的开始处放置以下内容:
You can use delayed expansion to correct the issue. Put the following at the start of your batch:
setlocal enabledelayedexpansion
,然后在循环中使用!date!
和!time!
.这样将在执行语句之前扩展变量,从而可以按预期工作.
and then use !date!
and !time!
within the loop. This will expand the variables just prior to executing a statement and thus will work as intended.
这篇关于正确地为批处理脚本创建的日志文件添加时间戳的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!