监视文件更改的批处理脚本
Batch script that monitors for file changes
我需要创建一个批处理脚本来持续监视特定文件的更改,在本例中为 LogTest.txt。
更新文件时,它会触发一个 VBScript 消息框,显示 LogTest.txt 中的最后一行。思路是这样清除消息框后继续监听
我试过使用 forfiles
选项,但这实际上只能让我处理日期而不是时间。我知道可以使用 PowerShell 和其他选项,但由于太长无法解释的原因,我仅限于只能使用批处理和 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 在每次对文件的写入访问时设置此属性。
您可以使用 attrib
命令设置它并检查它,例如:
@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-负载的小等待间隔(永远不要在没有空闲时间的情况下构建循环)
for %%i in (logTest.txt) do
...处理文件
echo %%~ai
打印属性(详见for /?
)
|find "a" >nul
尝试在前一个 echo
的输出中找到 "a"rchive-attribute 并将任何输出重定向到 nirvana(我们不需要它,只需要 errorlevel )
|| goto :loop
相当于 "if previous command (find
) failed, then start again at the label :loop
"
如果find
成功(是存档属性),那么将处理下一行(echo file was changed
...)
attrib -a LogTest.txt
取消设置文件的存档属性。
我需要创建一个批处理脚本来持续监视特定文件的更改,在本例中为 LogTest.txt。
更新文件时,它会触发一个 VBScript 消息框,显示 LogTest.txt 中的最后一行。思路是这样清除消息框后继续监听
我试过使用 forfiles
选项,但这实际上只能让我处理日期而不是时间。我知道可以使用 PowerShell 和其他选项,但由于太长无法解释的原因,我仅限于只能使用批处理和 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 在每次对文件的写入访问时设置此属性。
您可以使用 attrib
命令设置它并检查它,例如:
@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-负载的小等待间隔(永远不要在没有空闲时间的情况下构建循环)
for %%i in (logTest.txt) do
...处理文件
echo %%~ai
打印属性(详见for /?
)
|find "a" >nul
尝试在前一个 echo
的输出中找到 "a"rchive-attribute 并将任何输出重定向到 nirvana(我们不需要它,只需要 errorlevel )
|| goto :loop
相当于 "if previous command (find
) failed, then start again at the label :loop
"
如果find
成功(是存档属性),那么将处理下一行(echo file was changed
...)
attrib -a LogTest.txt
取消设置文件的存档属性。