# Batch File to run when a file gets modified



## Avilash

I need a batch file which should run automatically as and when a file gets modified.

The main goal is to copy the file. But it should run automatically when the file gets modified. Any kind of help will be helpful for me.


----------



## TheOutcaste

Welcome to TSF!

Google for Folder Monitor or Folder Watch, there's tons of freeware/paid software.

I played with a couple a while back and these come to mind:
Folder Monitor 2.0
Folder Watchdog Service 2

The Watchdog service can send you an email, or run a file to take whatever action you want.

You can also use a batch file or VB Script to monitor a folder, and take an action.
http://blogs.technet.com/heyscripti...ent-types-of-events-with-just-one-script.aspx
http://blogs.technet.com/heyscripti...older-for-the-creation-of-new-subfolders.aspx

This batch file will monitor a single file, files with the same extension, or an entire directory tree for any changes: new files, files deleted, change in size, change in modified date.
It will not detect changes that occur when it's not running, but it would be easy to have it check to see if a baseline has been saved, and use that to detect if changes occured while it wasn't running.
It checks the folder every 10 seconds
Specify the full path to the folder or file in the *_Monitor* line


Code:


@Echo Off
Set _Delay=10
[COLOR=Red]Set _Monitor=E:\Scripts[/COLOR]
Set _Base=%temp%\BaselineState.dir
Set _Chck=%temp%\ChkState.dir
Set _OS=6
Ver|Findstr /I /C:"Version 5">Nul
If %Errorlevel%==0 Set _OS=5 & Set /A _Delay=_Delay*1000
:_StartMon
Call :_SetBaseline "%_Base%" "%_Monitor%"
:_MonLoop
If %_OS%==5 (Ping 1.0.0.0 -n 1 -w %_Delay%>Nul) Else Timeout %_Delay%>Nul
Call :_SetBaseline "%_Chck%" "%_Monitor%"
FC /A /L "%_Base%" "%_Chck%">Nul
If %ErrorLevel%==0 Goto _MonLoop
[COLOR=Red]::
:: Insert code to run when a change occurs
::
Echo.Change Detected[/COLOR]
Goto :_StartMon
:::::::::::::::::::::::::::::::::::::::::::::::::::
:: Subroutine
:::::::::::::::::::::::::::::::::::::::::::::::::::
:_SetBaseline
If Exist "%temp%\tempfmstate.dir" Del "%temp%\tempfmstate.dir"
For /F "Tokens=* Delims=" %%I In ('Dir /S "%~2"') Do (
Set _Last=%%I
>>"%temp%\tempfmstate.dir" Echo.%%I
)
>"%~1" Findstr /V /C:"%_Last%" "%temp%\tempfmstate.dir"
Goto :EOF


----------

