VBScript WQL Sort Result Set?

2.5k views Asked by At

Apparently WQL does not contain an ORDER BY clause. Is there a way to sort the result set based on one of the columns? For example:

Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\.\root\cimv2")
sSQL = "Select Time,Source,Event,CategoryNum,Category,TypeNum,Type,User,ComputerName,Insertion1,Insertion2,Data from Win32_NTLogEvent Where Logfile = 'System' and SourceName = 'Service Control Manager'"
Set resultSet = objWMIService.ExecQuery (sSQL)
For Each objEvent In resultSet
    ...
Next

Is there a way to sort resultSet by the Time column?

1

There are 1 answers

6
Ansgar Wiechers On

WQL indeed doesn't have an ordering clause, so sorting directly in the query is not possible. What you can do is put the returned data in a disconnected recordset and then sort the recordset:

Set DataList = CreateObject("ADOR.Recordset")
DataList.Fields.Append "Time", 7
DataList.Fields.Append "Source", 200, 255
DataList.Fields.Append "Event", 3
...
DataList.Open

Set wmi = GetObject("winmgmts:{impersonationLevel=impersonate}!//./root/cimv2")
qry = "SELECT Time,Source,Event,CategoryNum,Category,TypeNum,Type,User,ComputerName,Insertion1,Insertion2,Data " & _
      "FROM Win32_NTLogEvent " & _ 
      "WHERE Logfile='System' AND SourceName='Service Control Manager'"

For Each evt In wmi.ExecQuery(qry)
    DataList.AddNew
    DataList("Time")   = evt.Time
    DataList("Source") = evt.Source
    DataList("Event")  = evt.Event
    ...
    DataList.Update
Next

DataList.Sort = "Time"
DataList.MoveFirst
Do Until DataList.EOF
    WScript.Echo DataList.Fields.Item("Time") & vbTab & _
        DataList.Fields.Item("Event")
    DataList.MoveNext
Loop

Adjust the data type of the fields as required.