-1

I need a way to track updates/modifications to a file in real time and run a batch script when they take place, I have tried this to no avail, which may be due to it being open in the program that is logging output to the file, but

Get-content filename -Tail 0 -Wait

in powershell will show me any updates that happen to the file, is there any way for me to make it launch a script when a change is detected or any other way to do so. I need it to be in either batch or powershell script. Thanks for any and all help.

1 Answers1

0

Instead of tail why not just periodically do this first batch file:

REM 60 second looping check on TARGETFILE for a change of that file
:TOP
copy dir-out dir-out.old  
if errorlevel = 2 dir TARGETFILE > dir-out.old
dir TARGETFILE > dir-out  
fc dir-out dir-out.old 
if errorlevel = 1 goto:EOF
sleep 60s
goto:TOP
:EOF 
NAMEOFSECONDBATCHFILE.BAT

Step 1: copy dir-out dir-out.old uses the copy command which is a part of Windows to make a copy of the old copy of the directory listing. If there is no file dir-out then you will get an errorlevel value of 2; more on that later.

Step 2: if errorlevel = 2 dir TARGETFILE > dir-out.old

The first time you run this script, there won't be a file named **dir-out.old*, so we make one to prime the pump and keep the script from breaking. errorlevel is also a part of Windows.

Step 3: dir TARGETFILE > dir-out uses the dir command which is a part of Windows to get a directory listing about TARGETFILE which is the file you want to watch; replace TARGETFILE with the name of the file you wish to track

Step 4: fc dir-out dir-out.old uses the fc command which is a part of Windows to compare the directory listing you just made 'dir-out', to the previous version of that directory listing 'dir-out.old'. If they're the same, the value of the variable errorlevel = 0. If they're not the same, the value of the variable errorlevel changes to 1.

Step 5: if errorlevel = 1 goto:EOF when a change is detected go to the end of this batch file to launch your second script SECONDBATHFILE.BAT

Step 6: sleep 60s relies on a free, open source utility sleep which you get from http://gnuwin32.sourceforge.net/packages/coreutils.htm Windows does not have a utility to wait for a specific time, so we get a reliable utility and add it into c:\Windows\System32 or somewhere else in your path. The value 60 here is arbitrary and you can change that to whatever you want.

Step 7: OK, you've slept; time to check again. Go back to the top of the loop.

Step 8: EOF is a marker. You only go here when a change in TARGETFILE is found.

Step 9: NAMEOFSECONDBATCHFILE.BAT is also named arbitrarily and you can change it to whatever you want. That's the name of the batch file to do whatever you want done when a file change is detected.

K7AAY
  • 9,725