Working with System Processes in WSH - More fun with processes
(Page 3 of 4 )
To this point, everything we've done has been in a snapshot state. By this I mean that we have only been able to work with the processes that are running at the moment our script is executed.
What if we want a script to monitor processes and notify us whenever one starts or stops? To do this, we can use the Win32_Process class with a bit of event-based programming.
strProcess = "iexplore.exe"
strComputer = "."
Set objWMIService = GetObject("winmgmts: " _
"{impersonationLevel=impersonate}!" & strComputer _
& "rootcimv2")
Set objEventSrc = objWMIService.ExecNotificationQuery( _
"SELECT * FROM __InstanceCreationEvent " & _
"WITHIN 1 WHERE TargetInstance ISA 'Win32_Process'" _
& "And TargetInstance.Name = '" & strProcess & "'")
Do While True
Set objEvent = objEventSrc.NextEvent()
WScript.Echo strProcess & " has been started."
Exit Do
Loop
Event scripting is slightly beyond the scope of this article. Understand that WMI is able to monitor certain events. In this example we are monitoring the __InstanceCreationEvent which tells WMI whenever a new object is created in memory. We then use a notification query to check whether that particular event was our process starting.
Notice how we've used an infinite loop to ensure that our script doesn't stop running. Thus it will continue to monitor each new event until Internet Explorer is started.
strProcess = "iexplore.exe"
strComputer = "."
Set objWMIService = GetObject("winmgmts: " _
"{impersonationLevel=impersonate}!" & strComputer _
& "rootcimv2")
Set objEventSrc = objWMIService.ExecNotificationQuery( _
"SELECT * FROM __InstanceDeletionEvent " & _
"WITHIN 1 WHERE TargetInstance ISA 'Win32_Process'" _
& "And TargetInstance.Name = '" & strProcess & "'")
Do While True
Set objEvent = objEventSrc.NextEvent
WScript.Echo strProcess & " has been stopped."
Exit Do
Loop
Waiting for a process to end is exactly the same except that we will be watching the __InstanceDeletionEvent to know when a process is unloaded from memory instead.
Again, the nature of how this code works is a bit beyond the scope of this article. Just understand that this is the basic query structure you will need to use. You can modify this query slightly to achieve other effects as well so don't be afraid to play with it. For more information, you can check out my articles on event scripting with WMI.
Event Scripting with WMI
More Event Scripting with WMI
Next: Modifying processes >>
More Windows Scripting Articles
More By Nilpo