WinBatch® Technical Support Forum

All Things WinBatch => WinBatch => Topic started by: spl on September 10, 2025, 10:10:50 AM

Title: WMI System Event Class
Post by: spl on September 10, 2025, 10:10:50 AM
Not sure, initially, how something like this is helpful, but then someone reading and/or testing might weigh in on that. The code below will create a subscription to an event monitoring every 5 seconds for the creation of a new Win32-Process. The script will terminate after a new process is detected with a Message(), but would normally run the duration of the script [which can be adjusted for with cancel code]. Might be useful as a udf looking for a certain process to initiate... dunno
;Stan Littlefield 9/10/2025 (using WB2025C)
;Test with WMI system event class
;using __InstanceCreationEvent
;but also could use:
;__InstanceOperationEvent __InstanceModificationEvent __InstanceDeletionEvent
;===========================================================================
IntControl(73,1,0,0,0)
GoSub UDFS
Computer = "."
objLocator = ObjectCreate("WbemScripting.SWbemLocator")
objServices = objLocator.ConnectServer(Computer, "root\cimv2")
strQuery = "SELECT * FROM __InstanceCreationEvent WITHIN 5 WHERE TargetInstance ISA 'Win32_Process'"
objEventSource = objServices.ExecNotificationQuery(strQuery)
Display(5,"WMI Event Monitor", "Waiting 5 seconds for a new process to start...")
; Wait for the next event
objEvent = objEventSource.NextEvent()
; Extract details from the event
strProcessName = objEvent.TargetInstance.Name
strProcessID = objEvent.TargetInstance.ProcessId
Message("New Process Detected", "Name: " : strProcessName : @CRLF : "PID: " : strProcessID)
Exit

:WBERRORHANDLER
geterror()
Terminate(@TRUE,"Error Encountered",errmsg)
;===========================================================================
:UDFS

#DefineSubRoutine geterror()
   wberroradditionalinfo = wberrorarray[6]
   lasterr = wberrorarray[0]
   handlerline = wberrorarray[1]
   textstring = wberrorarray[5]
   linenumber = wberrorarray[8]
   errmsg = "Error: ":lasterr:@LF:textstring:@LF:"Line (":linenumber:")":@LF:wberroradditionalinfo
   Return(errmsg)
#EndSubRoutine

Return