Search This Blog

Wednesday 11 May 2016

Email alert for empty folders

A customer asked how he can setup our program WatchDirectory to notify him when a folder is created and no files are present after a few hours.
WatchDirectory is typically used to detect new files or folders so this requires a little scripting to get right.

Setup the Email task

Create a new task based upon the Email Plugin. Use something like "Folder %WD_FILE_N% is empty after 2 hours" as the subject and "%WD_FILE% is empty" somewhere inside the email body.
%WD_FILE% is replaced with the full path (C:\Some\Folder) of the new directory, WD_FILE_N by the directory name without its path (just "Folder"). See Variables for all variables you can use.

For the Monitoring Method select File Age, let it trigger for files (it also does directories) older than 120 minutes. Make sure to check the option "Remember triggered files" unless you want to receive multiple alerts as the folder gets older and older.

On Events only select "DIRNEW" - to detect folders, we are not interested in files.

The Script that actually checks for empty folders

WatchDirectory can not do everything for everyone just by installing but it has amazing ways how you can customize its functionality with little scripts. In this case the customer wants to receive a notification when a folder is empty after X hours, something not directly supported ("build in") by WatchDirectory.

On Filter Events you can add several standard filters to prevent triggering the WatchDirectory task (for example, the file or directory must match "Customer_*.txt"), for this case we need a filter script (a .bat file).
Here is the script to use in this case:

rem filter script that checks if a detected "new" directory is empty
rem "new" in quotes because WatchDirectory triggers using the File Age
rem monitoring method for directories that are 2 hours old.
rem When the directory is empty, the task should trigger an email.
rem If the directory contains one or more files, no email should be sent.

rem %WD_...% variables are explained here: 
rem     http://www.watchdirectory.net/wdhelp/plugins/wdopAutoRunBatEnv.html
rem File Age Monitoring:
rem     http://www.watchdirectory.net/wdhelp/help/wdnewconfigpage3.html
rem Filter Scripts:
rem     http://www.watchdirectory.net/wdhelp/help/filter_events.html

IF "%WD_REASON%" NEQ "DIRNEW" GoTo :NoTrigger

SET NUMFILE=0
FOR %%c IN ("%WD_FILE%\*.*") DO Call :FoundFile
IF %NUMFILE% EQU 0 GOTO :Trigger
GOTO :NoTrigger

:FoundFile
SET /A NUMFILE=NUMFILE + 1
GOTO :EOF

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

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

No comments: