Monthly Archives: March 2013

Use WMI to find and terminate a process by it’s EXE filename

This function will take a filepath to an executable, which can be discovered from the registry, and terminate any process using that executable.

Public Function WMICloseProgram(ByVal fileName As String) As Boolean
 On Error GoTo ErrorHandler
 Dim wmi As Object
 Set wmi = GetObject("winmgmts:{impersonationLevel=impersonate}!\\.\root\cimv2")
 'Use winmgmts to access full process list
 fileName = Replace(fileName, "\", "\\")
 Dim query As String
 query = "Select * from Win32_Process Where ExecutablePath = '" + fileName + "'"
 Dim results As Object
 Set results = wmi.ExecQuery(query)
 If results.Count > 0 Then
    'At least one matching result
    Dim process As Object
    For Each process In results
 WMICloseProgram = True
 End If
 If (Err.Number <> 0) Then WMICloseProgram = False
 Set wmi = Nothing
End Function