监视文件更改的批处理脚本 [英] Batch script that monitors for file changes
问题描述
我需要创建一个批处理脚本来持续监视特定文件的更改,在本例中为 LogTest.txt.
I need to create a batch script that continually monitors a specific file for changes, in this case, LogTest.txt.
当文件更新时,它会触发一个 VBScript 消息框,显示 LogTest.txt 中的最后一行.这个想法是在清除消息框后这将继续监视.
When the file is updated it will trigger a VBScript message box, which displays the last line from within LogTest.txt. The idea is that this will continue monitoring after the message box is cleared.
我曾尝试使用 forfiles
选项,但这实际上只能让我处理日期而不是时间.我知道可以使用 PowerShell 和其他选项,但由于太长而无法解释的原因,我只能使用批处理和 VBScript.
I have tried using the forfiles
option, but this really only lets me deal with the date and not the time. I know that PowerShell and other options are available, but for reasons that are just too long to explain I am limited to being only able to use a batch and VBScript.
批处理文件:
@echo off
:RENEW
forfiles /m LogTest.txt /d 0
if %errorlevel% == 0 (
echo The file was modified today
forfiles /M LogTest.txt /C "cmd /c echo @file @fdate @ftime"
cscript MessageBox.vbs "Error found."
REM do whatever else you need to do
) else (
echo The file has not been modified today
dir /T:W LogTest.txt
REM do whatever else you need to do
)
goto :RENEW
MessageBox.vbs
:
Set objArgs = WScript.Arguments
messageText = objArgs(0)
MsgBox "This is an error", vbOkCancel + vbExclamation, "Error Found"
推荐答案
每个文件都有一个存档属性.Windows 会在每次对文件进行写访问时设置此属性.
There is an archive attribute on every file. Windows sets this attribute on every write access to the file.
您可以使用 attrib
命令设置它并检查它,例如:
You can set it with the attrib
command and check it for example with:
@echo off
:loop
timeout -t 1 >nul
for %%i in (LogTest.txt) do echo %%~ai|find "a">nul || goto :loop
echo file was changed
rem do workload
attrib -a LogTest.txt
goto :loop
timeout/t 1 >nul
:小的等待间隔以减少 CPU 负载(不要在没有空闲时间的情况下构建循环)
timeout /t 1 >nul
: small wait interval to reduce CPU-Load (never build a loop without some idle time)
for %%i in (logTest.txt) do
...处理文件
echo %%~ai
打印属性(详见for/?
)
|find "a" >nul
尝试在前一个 echo
的输出中找到 "a"rchive-attribute 并将任何输出重定向到 nirvana(我们不需要它,只是错误级别)
|find "a" >nul
try to find the "a"rchive-attribute in the output of the previous echo
and redirect any output to nirvana (we don't need it, just the errorlevel)
<代码>||goto :loop 的作用类似于如果上一个命令 (find
) 失败,则从标签 :loop
重新开始"
|| goto :loop
works as "if previous command (find
) failed, then start again at the label :loop
"
如果 find
成功(是存档属性),那么下一行将被处理(echo file was changed
...)
If find
was successful (there is the archive attribute), then the next lines will be processed (echo file was changed
...)
attrib -a LogTest.txt
取消设置文件的存档属性.
attrib -a LogTest.txt
unsets the archive attribute of the file.
这篇关于监视文件更改的批处理脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!