Can't find the information you are looking for here? Then leave a message over on our WinBatch Tech Support Forum.
Keywords: watchdir watch a directory monitor a folder
;The following query watches for notification that a file has been added or deleted to/from a folder. strComputer = "." objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" : strComputer : "\root\cimv2") colMonitoredEvents = objWMIService.ExecNotificationQuery (`SELECT * FROM __InstanceOperationEvent WITHIN 10 WHERE Targetinstance ISA 'CIM_DirectoryContainsFile' and TargetInstance.GroupComponent= 'Win32_Directory.Name="c:\\\\Temp"'`) While @TRUE objLatestEvent = colMonitoredEvents.NextEvent class = objLatestEvent.Path_.Class component = objLatestEvent.TargetInstance.PartComponent file = StrReplace( StrTrim(ItemExtract( 2, component, '=' )), '\\', '\' ) Select @TRUE Case class == "__InstanceCreationEvent" Pause("A new file was just created:", file ) Break Case class == "__InstanceDeletionEvent" Pause("A file was just deleted:", file ) Break EndSelect EndWhile
WatchDir = (The directory you want To watch) Kernel32 = DllLoad(StrCat(DirWindows(1),"KERNEL32.DLL")) WatchHandle = DllCall(Kernel32,long:"FindFirstChangeNotificationA",lpstr:WatchDir,long:1,long:1) Status = DllCall(kernel32,long:"WaitForSingleObject",long:WatchHandle,long:-1) DllCall(Kernel32,long:"FindCloseChangeNotification",long:WatchHandle) DllFree(Kernel32) Message ("Hello!","Something Changed!")
GENERIC_READ = 2147483648 GENERIC_WRITE = 1073741824 INVALID_HANDLE_VALUE = -1 FILE_SHARE_READ = 1 ; Enables subsequent open operations on a file or device to ; request read access. ; Otherwise, other processes cannot open the file or device if ; they request read access. ; If this flag is not specified, but the file or device has ; been opened for read access, the function fails FILE_SHARE_WRITE = 2 ; Enables subsequent open operations on a file or device to ; request write access ; Otherwise, other processes cannot open the file or device if ; they request write access. ; If this flag is not specified, but the file or device has ; been opened for write access or has a file mapping with write ; access, the function fails FILE_SHARE_DELETE = 4 ; Enables subsequent open operations on a file or device to ; request delete access. ; Otherwise, other processes cannot open the file or device if ; they request delete access. ; If this flag is not specified, but the file or device has ; been opened for delete access, the function fails. ; Note: Delete access allows both delete and rename operations CREATE_NEW = 1 ; Creates a new file, only if it does not already exist. ; If the specified file exists, the function fails and the ; last-error code is set to ERROR_FILE_EXISTS (80). ; If the specified file does not exist and is a valid path to a ; writable location, a new file is created CREATE_ALWAYS = 2 ; Creates a new file, always. ; If the specified file exists and is writable, the function ; overwrites the file, the function succeeds, and last-error ; code is set to ERROR_ALREADY_EXISTS (183). ; If the specified file does not exist and is a valid path, a ; new file is created, the function succeeds, and the ; last-error code is set to zero. OPEN_EXISTING = 3 ; Opens a file or device, only if it exists. ; If the specified file or device does not exist, the function ; fails and the last-error code is set to ; ERROR_FILE_NOT_FOUND (2) OPEN_ALWAYS = 4 ; Opens a file, always. ; If the specified file exists, the function succeeds and the ; last-error code is set to ERROR_ALREADY_EXISTS (183). ; If the specified file does not exist and is a valid path to ; a writable location, the function creates a file and the ; last-error code is set to zero. TRUNCATE_EXISTING = 5 ; Opens a file and truncates it so that its size is zero bytes, ; only if it exists. ; If the specified file does not exist, the function fails and ; the last-error code is set to ERROR_FILE_NOT_FOUND (2). ; The calling process must open the file with the GENERIC_WRITE ; bit set as part of the dwDesiredAccess parameter FILE_ATTRIBUTE_READONLY = 1 ; The file is read only. Applications can read the file, but ; cannot write to or delete it FILE_ATTRIBUTE_HIDDEN = 2 ; The file is hidden. Do not include it in an ordinary ; directory listing FILE_ATTRIBUTE_SYSTEM = 4 ; The file is part of or used exclusively by an operating ; system FILE_ATTRIBUTE_DIRECTORY = 16 ; The handle that identifies a directory FILE_ATTRIBUTE_ARCHIVE = 32 ; The file should be archived. Applications use this attribute ; to mark files for backup or removal FILE_ATTRIBUTE_DEVICE = 64 ; This value is reserved for system use FILE_ATTRIBUTE_NORMAL = 128 ; The file does not have other attributes set. This attribute ; is valid only if used alone FILE_ATTRIBUTE_TEMPORARY = 256 ; The file is being used for temporary storage FILE_ATTRIBUTE_SPARSE_FILE = 512 ; A file that is a sparse file FILE_ATTRIBUTE_REPARSE_POINT = 1024 ; A file or directory that has an associated reparse point, or ; a file that is a symbolic link FILE_ATTRIBUTE_COMPRESSED = 2048 ; A file or directory that is compressed. For a file, all of ; the data in the file is compressed. ; For a directory, compression is the default for newly created ; files and subdirectories. FILE_ATTRIBUTE_OFFLINE = 4096 ; The data of a file is not immediately available. This ; attribute indicates that file data is physically moved to ; offline storage. This attribute is used by Remote Storage, ; the hierarchical storage management software. Applications ; should not arbitrarily change this attribute FILE_ATTRIBUTE_NOT_INDEXED = 8192 ; The file or directory is not to be indexed by the content ; indexing service FILE_ATTRIBUTE_ENCRYPTED = 16384 ; The file or directory is encrypted. For a file, this means ; that all data in the file is encrypted. For a directory, this ; means that encryption is the default for newly created files ; and subdirectories. ; This flag has no effect if FILE_ATTRIBUTE_SYSTEM is also ; specified FILE_ATTRIBUTE_VIRTUAL = 65536 ; This value is reserved for system use FILE_FLAG_BACKUP_SEMANTICS = 33554432 ; The file is being opened or created for a backup or restore ; operation. ; The system ensures that the calling process overrides file ; security checks when the process has SE_BACKUP_NAME and ; SE_RESTORE_NAME privileges ; You must set this flag to obtain a handle to a directory. ; A directory handle can be passed to some functions instead of ; a file handle FILE_FLAG_DELETE_ON_CLOSE = 67108864 ; The file is to be deleted immediately after all of its ; handles are closed, which includes the specified handle and ; any other open or duplicated handles. ; If there are existing open handles to a file, the call fails ; unless they were all opened with the FILE_SHARE_DELETE share ; mode. ; Subsequent open requests for the file fail, unless the ; FILE_SHARE_DELETE share mode is specified FILE_FLAG_NO_BUFFERING = 536870912 ; The file or device is being opened with no system caching for ; data reads and writes. This flag does not affect hard disk ; caching or memory mapped files. ; There are strict requirements for successfully working with ; files opened with CreateFile using the FILE_FLAG_NO_BUFFERING ; flag, for details see File Buffering (MSDN) FILE_FLAG_OPEN_NO_RECALL = 1048576 ; The file data is requested, but it should continue to be ; located in remote storage. ; It should not be transported back to local storage. ; This flag is for use by remote storage systems. FILE_FLAG_OPEN_REPARSE_POINT = 2097152 ; Normal reparse point processing will not occur; CreateFile ; will attempt to open the reparse point. When a file is ; opened, a file handle is returned, whether or not the filter ; that controls the reparse point is operational. ; This flag cannot be used with the CREATE_ALWAYS flag. ; If the file is not a reparse point, then this flag is ; ignored. FILE_FLAG_OVERLAPPED = 1073741824 ; The file or device is being opened or created for ; asynchronous I/O. ; When subsequent I/O operations are completed on this handle, ; the event specified in the OVERLAPPED structure will be set ; to the signaled state. ; If this flag is specified, the file can be used for ; simultaneous read and write operations. ; If this flag is not specified, then I/O operations are ; serialized, even if the calls to the read and write functions ; specify an OVERLAPPED structure. ; For information about considerations when using a file handle ; created with this flag, see the Synchronous and Asynchronous ; I/O Handles FILE_FLAG_POSIX_SEMANTICS = 16777216 ; Access will occur according to POSIX rules. ; This includes allowing multiple files with names, differing ; only in case, for file systems that support that naming. ; Use care when using this option, because files created with ; this flag may not be accessible by applications that are ; written for MS-DOS or 16-bit Windows FILE_FLAG_RANDOM_ACCESS = 268435456 ; Access is intended to be random. The system can use this as a ; hint to optimize file caching. ; This flag has no effect if the file system does not support ; cached I/O and FILE_FLAG_NO_BUFFERING FILE_FLAG_SEQUENTIAL_SCAN = 134217728 ; Access is intended to be sequential from beginning to end. ; The system can use this as a hint to optimize file caching. ; This flag should not be used if read-behind (that is, ; backwards scans) will be used. ; This flag has no effect if the file system does not support ; cached I/O and FILE_FLAG_NO_BUFFERING FILE_FLAG_WRITE_THROUGH = 2147483648 ; Write operations will not go through any intermediate cache, ; they will go directly to disk FILE_NOTIFY_CHANGE_FILE_NAME = 1 ; Any file name change in the watched directory or subtree ; causes a change notification wait operation to return. ; Changes include renaming, creating, or deleting a file FILE_NOTIFY_CHANGE_DIR_NAME = 2 ; Any directory-name change in the watched directory or subtree ; causes a change notification wait operation to return. ; Changes include creating or deleting a directory FILE_NOTIFY_CHANGE_ATTRIBUTES = 4 ; Any attribute change in the watched directory or subtree ; causes a change notification wait operation to return FILE_NOTIFY_CHANGE_SIZE = 8 ; Any file-size change in the watched directory or subtree ; causes a change notification wait operation to return. ; The operating system detects a change in file size only when ; the file is written to the disk. ; For operating systems that use extensive caching, detection ; occurs only when the cache is sufficiently flushed FILE_NOTIFY_CHANGE_LAST_WRITE = 16 ; Any change to the last write-time of files in the watched ; directory or subtree causes a change notification wait ; operation to return. ; The operating system detects a change to the last write-time ; only when the file is written to the disk. ; For operating systems that use extensive caching, detection ; occurs only when the cache is sufficiently flushed FILE_NOTIFY_CHANGE_LAST_ACCESS = 32 ; Any change to the last access time of files in the watched ; directory or subtree causes a change notification wait ; operation to return FILE_NOTIFY_CHANGE_CREATION = 64 ; Any change to the creation time of files in the watched ; directory or subtree causes a change notification wait ; operation to return FILE_NOTIFY_CHANGE_SECURITY = 256 ; Any security-descriptor change in the watched directory or ; subtree causes a change notification wait operation to return ;typedef struct _SECURITY_ATTRIBUTES { ; DWORD nLength; ; LPVOID lpSecurityDescriptor; ; BOOL bInheritHandle; ;} ;CreateFile( ; __in LPCTSTR lpFileName, ; __in DWORD dwDesiredAccess, ; __in DWORD dwShareMode, ; __in_opt LPSECURITY_ATTRIBUTES lpSecurityAttributes, ; __in DWORD dwCreationDisposition, ; __in DWORD dwFlagsAndAttributes, ; __in_opt HANDLE hTemplateFile ;); ;ReadDirectoryChangesW ( ; __in HANDLE hDirectory, ; __out LPVOID lpBuffer, ; __in DWORD nBufferLength, ; __in BOOL bWatchSubtree, ; __in DWORD dwNotifyFilter, ; __out_opt LPDWORD lpBytesReturned, ; __inout_opt LPOVERLAPPED lpOverlapped, ; __in_opt LPOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine ;); ; FILE_NOTIFY_INFORMATION Structure ; Describes the changes found by the ReadDirectoryChangesW function. ; ; Syntax ; C++ typedef struct _FILE_NOTIFY_INFORMATION { ; DWORD NextEntryOffset; ; DWORD Action; ; DWORD FileNameLength; ; WCHAR FileName[1]; ; } FILE_NOTIFY_INFORMATION, *PFILE_NOTIFY_INFORMATION;Members ; NextEntryOffset ; The number of bytes that must be skipped to get to the next record. A value of zero indicates that this is the last record. ; ; Action ; The type of change that has occurred. This member can be one of the following values. ; ; Value Meaning ; FILE_ACTION_ADDED ; 0x00000001 The file was added to the directory. ; ; FILE_ACTION_REMOVED ; 0x00000002 The file was removed from the directory. ; ; FILE_ACTION_MODIFIED ; 0x00000003 The file was modified. This can be a change in the time stamp or attributes. ; ; FILE_ACTION_RENAMED_OLD_NAME ; 0x00000004 The file was renamed and this is the old name. ; ; FILE_ACTION_RENAMED_NEW_NAME ; 0x00000005 The file was renamed and this is the new name. ; ; ; FileNameLength ; The size of the file name portion of the record, in bytes. Note that this value does not include the terminating null character. ; ; FileName ; A variable-length field that contains the file name relative to the directory handle. The file name is in the Unicode character format and is not null-terminated. ; ; If there is both a short and long name for the file, the function will return one of these names, but it is unspecified which one. ; sDirPathToControl = "D:\TEMP\" iFlagsAndAttributes = FILE_ATTRIBUTE_ARCHIVE | FILE_ATTRIBUTE_HIDDEN | FILE_ATTRIBUTE_READONLY | FILE_ATTRIBUTE_SYSTEM | FILE_FLAG_BACKUP_SEMANTICS sKernel32 = StrCat (DirWindows (1), "KERNEL32.DLL") hDirectory = DllCall (sKernel32, Long : "CreateFileA", Lpstr : sDirPathToControl, Long : GENERIC_READ, Long : FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE, Lpnull, Long : OPEN_EXISTING, Long : iFlagsAndAttributes, Lpnull) lBufferLength = 1048576 pStructBuffer = BinaryAlloc (lBufferLength) BinaryEodSet (pStructBuffer, lBufferLength) pBytesReturned = BinaryAlloc (4) BinaryEodSet (pBytesReturned, 4) lNotifyFilter = FILE_NOTIFY_CHANGE_FILE_NAME | FILE_NOTIFY_CHANGE_DIR_NAME | FILE_NOTIFY_CHANGE_SIZE intResult = DllCall (sKernel32, Long : "ReadDirectoryChangesW", Long : hDirectory, Lpbinary : pStructBuffer, Long : lBufferLength, Long : @TRUE, Long : lNotifyFilter, Lpbinary : pBytesReturned, Lpnull, Lpnull) iReturnClose = DllCall (sKernel32, Long : "CloseHandle", Long : hDirectory) ; How many bytes have been given back? intBytesReturned = BinaryPeek4 (pBytesReturned,0) ; Break down the structure. intNextEntryOffset = BinaryPeek4 (pStructBuffer,0) intAction = BinaryPeek4 (pStructBuffer,4) intFileNameLength = BinaryPeek4 (pStructBuffer,8) strFileName = BinaryPeekStrW (pStructBuffer, 12, BinaryEodGet(pStructBuffer)) pBytesReturned = BinaryFree (pBytesReturned) pStructBuffer = BinaryFree (pStructBuffer) strMsgTitle = ItemExtract (intAction, "FILE_ACTION_ADDED,FILE_ACTION_REMOVED,FILE_ACTION_MODIFIED,FILE_ACTION_RENAMED_OLD_NAME,FILE_ACTION_RENAMED_NEW_NAME", ",") strMsgText = strFileName Message (strMsgTitle, strMsgText) Exit
Article ID: W15287
File Created: 2014:02:21:11:38:02
Last Updated: 2014:02:21:11:38:02