Previous Page
Next Page

Do...Loop

The Do...Loop statement is used to put a script into a loop for an undetermined number of loops. It causes the script to simply loop and loop and loop. In the DoLoopMonitorForProcessDeletion.vbs script, we use an additional event driven script. Here we use the Do...Loop structure, rather than using Do While True as in the MonitorForChangedDiskSpace.vbs script.

To use the DoLoopMonitorForProcessDeletion.vbs script, you will want to start up Notepad. Then you run the script. While the script is running, you can close out Notepad. Within 10 seconds, you will get a printed message that lists the name of the process, the process ID, and the amount of user mode time that was consumed. Because the script is a Do...Loop script, it will continue to run until you manually exit the script (by using Ctrl+C if you are running under CScript in a CMD prompt, or by killing the wscript.exe process in TaskManager if you are running the script in WScript). This means that if you open another instance of Notepad, wait for a few seconds, and then exit Notepad again, you will once again trigger an alert. You can obviously use this script to monitor more important processes than Notepad.exe. If you did not have the Do...Loop, the script would only alert you one time when a process exitednot a very tenable situation for a monitoring script.

DoLoopMonitorForProcessDeletion.vbs

Option Explicit
'On Error Resume Next
dim strComputer 'computer to run the script upon.
dim wmiNS 'the wmi namespace. Here it is the default namespace
dim wmiQuery 'the wmi event query
dim objWMIService 'SWbemServicesEx object
dim colItems 'SWbemEventSource object
dim objItem 'individual item in the collection
Dim objName ' monitored item. Any Process.
Dim objTGT 'monitored class. A win32_process.

strComputer = "."
objName = "'Notepad.exe'" 'the single quotes inside the double quotes required
objTGT = "'win32_Process'"
wmiNS = "\root\cimv2"
wmiQuery = "SELECT * FROM __InstanceDeletionEvent WITHIN 10 WHERE " _
    & "TargetInstance ISA " & objTGT & " AND " _
      & "TargetInstance.Name=" & objName

Set objWMIService = GetObject("winmgmts:\\" & strComputer & wmiNS)
Set colItems = objWMIService.ExecNotificationQuery(wmiQuery)
Do
  Set objItem = colItems.NextEvent
  Wscript.Echo "Name: " & objItem.TargetInstance.Name & " " & now
  Wscript.Echo "ProcessID: " & objItem.TargetInstance.ProcessId
  WScript.Echo "user mode time: " & objItem.TargetInstance.UserModeTime
Loop


Previous Page
Next Page