vbScript Implementation of FolderWatch

Reverend Jim

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.

About the Author

I completed my Computer Science degree at the University of Manitoba in 1976. I did two and a half years of programming in medical research followed by twenty-nine years at Manitoba Hydro (electric utility). Most of that was spent on doing development and maintenance on an AGC/SCADA (real-time programming/process control) system. The last ten years of that was spent doing application and infrastructure support and development. I have programmed in FORTRAN (mostly), APL, PL/1, COBOL, Lisp, SNOBOL, ALGOL, Assembler (several flavours), C, C++, Paradox, VB, vbScript and more recently, Python. I am married with two grown children of whom I am very proud, and a most beautiful wife. I am currently retired (and loving it).

''#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 = "."
    folder = WScript.Arguments(0)
    If Not fso.FolderExists(folder) Then
        WScript.Echo "Folder '" & folder & "' not found"
    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


End Sub
Be a part of the DaniWeb community

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