且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

监视文件更改的批处理脚本

更新时间:2023-12-05 19:52:10

每个文件都有一个存档属性.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.