vbScript Implementation of FolderWatch

Updated Reverend Jim 1 Tallied Votes 1K Views Share

An often underused control from vb.Net is the FolderWatch control. But sometimes you need to throw something together that doesn't need a fancy GUI. Or perhaps the task seems too trivial to go to the hassle of coding it up in vb.Net (or C#). Because the FolderWatcher is built on underlying WMI (Windows Management Instrumentation) technology, it can actually be implemented quite simply from vbScript. Please see the sample below.

In actual use you would place more useful code in the Create/Delete/Modify Case clauses.

.
''#region Header                                                                        '
''                                                                                      '
''  Name:                                                                               '
''                                                                                      '
''      FileWatch.vbs                                                                   '
''                                                                                      '
''  Description:                                                                        '
''                                                                                      '
''      Implements a Windows File Watch on a folder. This will report on an event Loop  '
''      (rather than a polling loop) the following events:                              '
''                                                                                      '
''          File Created                                                                '
''          File Deleted                                                                '
''          File Renamed (reported as delete/create)                                    '
''          File Modified                                                               '
''                                                                                      '
''  Audit:                                                                              '
''                                                                                      '
''      2018-02-19  rj  original code                                                   '
''                                                                                      '
''#endregion                                                                            '

Set fso = CreateObject("Scripting.FileSystemObject")

'Folder is either given by user or defaults to current folder

If WScript.Arguments.Count = 0 Then
    folder = "."
Else
    folder = WScript.Arguments(0)
    If Not fso.FolderExists(folder) Then
        WScript.Echo "Folder '" & folder & "' not found"
        WScript.Quit
    End If
End If

folder = fso.GetFolder(folder).Path

WScript.Echo "Watching folder '" & folder & "' for changes"
WScript.Echo "Press CTRL-C to stop"

WatchFolder fso.GetFolder(folder).Path

''Watch the given fully qualified folder for changes                                    '
Sub WatchFolder ( folder )

    Dim wmi         'Windows Management Instrumentation object  '
    Dim query       'wmi query for selecting events             '
    Dim events      'Collection of events from wmi              '
    Dim e           'Single event from collection               '
    Dim drive       'Drive letter (including :) from folder     '

    'A folder name for the query must have \\ instead of \ in the path, and
    'must also end with \\

    drive  = Left(folder,2)
    folder = Mid(folder,3)
    If Right(folder,1) <> "\" Then folder = folder & "\"
    folder = Replace(folder,"\","\\")

    'Set a value for WITHIN to report events within the given number of seconds. The
    'vbCrLf chars are not needed for the query but they make the displayed query
    'easier for a human to read.

    query = "SELECT * FROM __InstanceOperationEvent WITHIN 2" & vbCrLf _
          & "  WHERE Targetinstance ISA 'CIM_DataFile'"       & VbCrLf _
          & "    AND TargetInstance.Drive='" & drive  & "'"   & VbCrLf _
          & "    AND TargetInstance.Path='"  & folder & "'"
          
    WScript.Echo VbCrLf & query & VbCrLf
    
    'Get Windows Management Intrumentation (WMI) object and run query
    
    Set wmi = GetObject( "winmgmts:{impersonationLevel=impersonate}!\\.\root\cimv2" )
    Set events = wmi.ExecNotificationQuery(query)

    'This loop will suspend until events are reported for processing

    Do  'Press CTRL-C in console window to stop

        Set e = events.NextEvent()

        Select Case e.Path_.Class
            Case "__InstanceCreationEvent"
                WScript.Echo "Created: "  & e.TargetInstance.Name
            Case "__InstanceDeletionEvent"
                WScript.Echo "Deleted: "  & e.TargetInstance.Name
            Case "__InstanceModificationEvent"
                WScript.Echo "Modified: " & e.TargetInstance.Name
        End Select

    Loop

End Sub
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.