Jamie Mry
Jamie Mry

Reputation: 33

Batch script that monitors for file changes

I need to create a batch script that continually monitors a specific file for changes, in this case, 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.

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.

Batch File:

@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"

Upvotes: 3

Views: 9417

Answers (1)

Stephan
Stephan

Reputation: 56165

There is an archive attribute on every file. Windows sets this attribute on every write access to the file.

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: small wait interval to reduce CPU-Load (never build a loop without some idle time)

for %%i in (logTest.txt) do... process the file

echo %%~ai print the attributes (see for /? for details)

|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 works as "if previous command (find) failed, then start again at the label :loop"

If find was successful (there is the archive attribute), then the next lines will be processed (echo file was changed...)

attrib -a LogTest.txt unsets the archive attribute of the file.

Upvotes: 6

Related Questions