Search This Blog

Friday 4 February 2011

Is a WatchDirectory task Running?

Here is an example how you can check if a WatchDirectory task is running from inside a batch script. The example relies on Microsoft's Handle.exe to check if there is a wdrun.exe process that has the history database of the given task open.

The wdIsTaskRunning.bat Script

@echo off
rem this example script checks if a WatchDirectory task is running
rem usage:
rem  wdIsTaskRunning abc
rem     this checks if the task abc is running
rem  
rem This script uses Handle.exe ( http://technet.microsoft.com/en-us/sysinternals/bb896655 )
rem to see if the history.db file of the task is opened by a wdrun.exe process.
rem
SET HANDLE=C:\SysInternals\Handle.exe
SET TMPFILE=C:\Temp\handle_%RANDOM%.txt

"%HANDLE%" -p wdrun.exe \%1\history.db > "%TMPFILE%"
FINDSTR /L /C:"No matching handles found." "%TMPFILE%">NUL
if %errorlevel% equ 0 (
   echo The task %1 is NOT running
   SET TASKRUNNING=N
) else (
   echo The task %1 is running
   SET TASKRUNNING=Y
)
del "%TMPFILE%"

Alternative Implementation

The script above works for all WatchDirectory tasks but it needs Admin privileges to run handle.exe. If the task is configured to run as a Windows Service, you can also parse the output of the NET START command to see if the task is running.

@echo off
rem this example script checks if a WatchDirectory task is running
rem usage:
rem  wdIsTaskRunning abc
rem     this checks if the task abc is running
rem  
rem
SET TMPFILE=C:\Temp\netstart_%RANDOM%.txt

NET START > "%TMPFILE%"
FINDSTR /L /E /C:"watchDirectory:%1" "%TMPFILE%">NUL
if %errorlevel% equ 0 (
   echo The task %1 is running
   SET TASKRUNNING=Y
) else (
   echo The task %1 is NOT running
   SET TASKRUNNING=N
)
del "%TMPFILE%"

No comments: