Search This Blog

Wednesday, 12 March 2014

Filter Scrips - Slightly underdocumented

Q&A

WatchDirectory v4.7 and higher have support for filter scripts, run a little batch script to decide if a detected file should be processed by a task. This is a new option on the Filter Events settings of your task.

Before this new feature was introduced you could only filter based on (parts of) the filename or folder where the file was detected. For example "only run the task for files that match *.txt". The new filter script option gives you far more flexibility, your script receives all information about the detected file in Environment Variables and can, for example, check the contents of the detected file to decide wether the task should continue processing the file.

Several example filter scripts can be found inside the directory <Install Directory>\ExampleFilterScripts (typically C:\Program Files (x86)\watchDirectory\ExampleFilterScripts).

Example: Only email when files contain the word "Error"

A client was monitoring a directory where log files are created by an automated nightly process. Most log files are of no interest but sometimes one or two files contain error information and the client wants to be notified of those. He created a task using the Email plugin and enabled the option to attach the log file. Below is the filter script he used.

rem When called from the WatchDirectory Control Center, always process the "event"
IF "%WD_CALLEDFROMSETUP%" EQU "Y" GOTO :SayYes

rem use FINDSTR to check the contents of the file
FINDSTR /I "Error" "%WD_FILE%"
IF %errorlevel% EQU 0 GOTO :SayYes
rem this is not an error log, tell the task to ignore the event
GOTO :SayNo

:SayYes
ECHO Y > "%WD_FILTERRESULT%"
GOTO :EOF

:SayNo
ECHO N > "%WD_FILTERRESULT%"
GOTO :EOF

A few tips

Do not perform any heavy processing inside those scripts. If your script takes a long time to finish the WatchDirectory task will abort. A few seconds is okay, 10 seconds is not.

Make sure your script always writes its result (the single character Y or N) to the result file (echo Y > "%WD_FILTERRESULT%").

No comments: