Event Scripting with WMI - Using __InstanceCreationEvent
(Page 3 of 4 )
Next, you need to issue a query using the WMI Service object’s ExecNotificationQuery function.
Set colEvents = objWMIService.ExecNotificationQuery _
("SELECT * FROM __InstanceCreationEvent WITHIN 10 WHERE " _
& "Targetinstance ISA 'CIM_DirectoryContainsFile' AND " _
& "TargetInstance.GroupComponent= " _
& "'Win32_Directory.Name=""c:\test""'")
This query probably looks a lot different from the WMI queries to which you are accustomed. It’s a little complex, but I’ll try to simplify it for you. Here’s how it translates into English.
We’re looking for all (SELECT * FROM) creation events (__InstanceCreationEvent), WITHIN 10 seconds, WHERE the returned event (TargetInstance) is a (ISA) file contained in the C:test directory. (The remainder of the query).
It’s important to note that the WMI query will keep running. You must stop it by ending the script, otherwise it will continue indefinitely until the WMI Service is stopped.
Don’t forget that paths must be contained in quotation marks and all backslashes must be escaped with backslashes.
If you don’t fully understand this query, that’s okay. You can use it as a model for other queries just by changing the folder location.
So, WMI processes our request and returns a collection of events fitting our description that occurred within the timeout period.
Now we need to return the results. We’ll use the NextEvent function provided by the colEvents collection. Of course, there’s no way of knowing how many times our event occurred so we’ll enclose everything inside of an endless Do…Loop.
Do While True
Set objEvent = colEvents.NextEvent()
WScript.Echo "A new file was just created:", _
objEvent.TargetInstance.PartComponent
Exit Do
Loop
This Do Loop will continue forever. I’ve used the Exit Do statement to demonstrate how you can stop this process after one iteration. You could easily use a conditional statement to exit this as well.
If you only want to return a specific number of occurrences, try using a For…Next loop instead of the Do…Loop.
Even now, after ending the Do loop, our WMI query is still running. You can end it by quitting the script or by setting the objWMIService equal to Nothing if you want the script to continue running.
Next: Using __InstanceDeletionEvent >>
More Windows Scripting Articles
More By Nilpo/Developer Shed Staff Writer