Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How do I monitor subdirectories for WMI file creation events?

Status
Not open for further replies.

markhoward

Technical User
Jul 29, 2003
46
GB

The following code monitors for all files created or deleted in C:\Scripts.

Does anyone know how I can extend this to files or folders created anywhere within of the subfolders of a root point?

strComputer = "."
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")

Set colMonitoredEvents = objWMIService.ExecNotificationQuery _
("SELECT * FROM __InstanceOperationEvent WITHIN 10 WHERE " _
& "Targetinstance ISA 'CIM_DirectoryContainsFile' and " _
& "TargetInstance.GroupComponent= " _
& "'Win32_Directory.Name=""c:\\\\scripts""'")

Do While TRUE
Set objEventObject = colMonitoredEvents.NextEvent()

Select Case objEventObject.Path_.Class
Case "__InstanceCreationEvent"
Wscript.Echo "A new file was just created: " & _
objEventObject.TargetInstance.PartComponent
Case "__InstanceDeletionEvent"
Wscript.Echo "A file was just deleted: " & _
objEventObject.TargetInstance.PartComponent
End Select
Loop
 
You can easily change what you have to monitor for folders. I'll play around with this on my free time to see if you can get both at the same time.

Code:
strComputer = "."
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")

Set colMonitoredEvents = objWMIService.ExecNotificationQuery _
    ("SELECT * FROM __InstanceOperationEvent WITHIN 10 WHERE " _
        & "Targetinstance ISA 'Win32_Directory' And Targetinstance.Path='\\scripts\\'" _
        & "And Targetinstance.Drive='c:'")
 
Do While True
    Set objEventObject = colMonitoredEvents.NextEvent()

    Select Case objEventObject.Path_.Class
        Case "__InstanceCreationEvent"
            Wscript.Echo "A new folder was just created: " & _
                objEventObject.TargetInstance.Name
        Case "__InstanceDeletionEvent"
            Wscript.Echo "A folder was just deleted: " & _
                objEventObject.TargetInstance.Name
    End Select
Loop

--------------------------------------------------------------------------------
dm4ever
My philosophy: K.I.S.S - Keep It Simple Stupid
 
Thanks dm4ever!

Basically I just need to to dynamically pick up on any file and/or folder events below a search root.

I tried using the LIKE operator within the WQL query but with unsuccessful results...
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top