1

I have a WMI query that notifies me on USB insertions, but I am trying to group the results of this query so that my handler can operate on a batch of these insertions, as opposed to one by one as they come in. WQL supports a GROUP WITHIN clause that I am trying to use, but anytime I try to use it, I get exceptions after I start my ManagementEventWatcher.

   //Working Query, But Doesn't Group
    string query = 
            "SELECT * FROM __InstanceCreationEvent " + 
            "WITHIN 2 " +
            "WHERE TargetInstance ISA 'Win32_PnpEntity'";
            

What I am trying to do is use GROUP WITHIN to group these insertion events so that instead of having my handler deal with one at a time, it can do it in batches.

Update: I have redone the query to match the syntax as shown on the documentation, however I still get an exception: "System.Runtime.InteropServices.COMException: 'Exception from HRESULT: 0x80042002'"

       //Doesn't work
       string insertionQuery =
     "SELECT * FROM __InstanceCreationEvent " +
     "WHERE TargetInstance ISA 'Win32_PnPEntity' GROUP WITHIN 60";

How I'm using the query:

            ManagementEventWatcher insertWatcher = new ManagementEventWatcher(query);
            insertWatcher.EventArrived += new EventArrivedEventHandler(USB_Insertion_EventArrived);
            insertWatcher.Start(); //Exception gets thrown 

Any help is appreciated!

TheJay
  • 11
  • 2
  • 1
    `GROUP WITHIN` needs to go at the end, after the `WHERE` clause: `SELET ... FROM ... WHERE ... ISA ... GROUP WITHIN ...` – Mathias R. Jessen May 13 '22 at 00:19
  • Duh, thank you! However, after using the proper syntax I still get an exception: "System.Runtime.InteropServices.COMException: 'Exception from HRESULT: 0x80042002'". I've edited my question to include this info – TheJay May 13 '22 at 02:20
  • I suggest to create the query using a `WqlEventQuery` object instead of writing the string yourself. -- When you specify a Group (`__AggregatedEvent`), you also need to specify a `WithinInterval` value (TimeSpan) that matches the class polling behavior. In your case, you probably want this interval to match the `GroupWithinInterval` TimeSpan value. -- Also, note that the timeout counter starts when the last event of the same type is received, within that interval, unless you also specify a `HavingCondition` that defines the `NumberOfEvents` to consider. – Jimi May 13 '22 at 07:24

1 Answers1

2

Take a look at the documented syntax:

SELECT * FROM EventClass [WHERE property = value] 
    GROUP WITHIN interval [BY property_list]
    [HAVING NumberOfEvents operator integer]

The WHERE clause must go immediately after the class name, the GROUP WITHIN statement goes at the end:

   string insertionQuery =
        "SELECT * FROM __InstanceCreationEvent " +
        "WHERE TargetInstance ISA 'Win32_PnPEntity' " +
        "GROUP WITHIN 60";
Mathias R. Jessen
  • 157,619
  • 12
  • 148
  • 206