This arose out of the incident where it was realized that WMI could not be expected to be reliable across all various computers. The next thing I looked at was API which was positively awful to work with. Based on a suggestion, I decided to try and use tasklist
. Note that efforts was made to ensure there are no disk I/Os, which avoids getting into the messy realms of file management. The only annoyance is that the WshExec
will pop open a window but that can be managed and is beyond the scope of the question.
The question is - can we make the process more reliable and failsafe? The idea is that it must be consistent across several computer systems, Windows versions, and so on. This makes uses of Windows Host Scripting Model and ADODB recordset. The application already requires ADODB anyway and the code can be updated to be late-bound as well. For testing/development, I left this in early-bound state.
Public Function EnumProcesses() As ADODB.Recordset
Dim WshShell As IWshRuntimeLibrary.WshShell
Dim WshExec As IWshRuntimeLibrary.WshExec
Dim StdOut As IWshRuntimeLibrary.TextStream
Dim Data As ADODB.Recordset
Dim Output As String
Dim ColumnLengths() As Long
Set Data = New ADODB.Recordset
Data.Fields.Append "ImageName", adVarChar, 255
Data.Fields.Append "PID", adInteger, , adFldKeyColumn
Data.Open
Set WshShell = CreateObject("WScript.Shell")
Set WshExec = WshShell.Exec("tasklist")
Set StdOut = WshExec.StdOut
Do While WshExec.Status = WshRunning
If Not StdOut.AtEndOfStream Then
Output = StdOut.ReadLine
Select Case True
Case Len(Output) = 0, _
Output Like "Image Name*"
'Skip
Case Output Like "====*"
Dim SplitColumns As Variant
SplitColumns = Split(Output, " ")
ReDim ColumnLengths(UBound(SplitColumns))
Dim i As Long
For i = 0 To UBound(SplitColumns)
ColumnLengths(i) = Len(SplitColumns(i))
Next
Case Else
Data.AddNew
Data.Fields("ImageName").Value = Mid$(Output, 1, ColumnLengths(0))
Data.Fields("PID").Value = Trim$(Mid$(Output, ColumnLengths(0) + 2, ColumnLengths(1)))
Data.Update
End Select
End If
Loop
Set EnumProcesses = Data
End Function