how can I identify and kill orphaned Excel instances in the Task Manager list

121 Views Asked by At

Somehow we periodically end up with an orphaned Excel instance in the Task Manager list. I can manually end the process, but I would like to figure out a way to identify them programmatically. Then I can use TaskKill with the specific PID to get rid of them.

Using an Admin Cmd window, the following 2 tasklist commands display what I am looking for

tasklist /fi "PID eq 12345" /fo csv > c:\Temp\MyExcelPIDTaskList.csv

tasklist /fi "ImageName eq Excel.exe" /fo csv > c:\Temp\MyExcelTaskList.csv

What is the script equivalent that I could put in a Windows Task Scheduler task to identify and kill the orphaned Excel task? I rarely work at this level so I apologize if my terminology is not quite right.

So it appears I may need something similar to the following:

`Set objWMI = GetObject("WinMgmts:{ImpersonationLevel=Impersonate}!\\.\Root\CIMV2")
 Set objOS  = objWMI.ExecQuery("SELECT * FROM Win32_Process")`

Am I on the right track? If so, how do I filter Win32_OperatingSystem by PID?

1

There are 1 best solutions below

0
j2associates On

After some more digging, I figured it out. First, there are a gazillion WMI Classes. Here is an excellent link I happened upon: WMI Samples. It has separate sections for VBScript, JScript, Powershell, Python and Perl. From the same source, here is a link for Win32_Process, which was the class I ultimately needed as well as for Microsoft's Win32_Process class.

An orphaned Excel PID (in my case) gets passed to the following VBScript code. It checks to ensure the PID still exists, and if it does, uses TaskKill to terminate the process.

    Const Debugging = False
    
    Set args = WScript.Arguments
    PID = CLng(args(0))
    If Debugging Then
        WScript.Echo PID
    End If
    
    ' Ensure the PID still exists.
    Set oWMI = GetObject("WinMgmts:{ImpersonationLevel=Impersonate}!\\.\Root\CIMV2")
    Set oProcesses = oWMI.ExecQuery("SELECT * FROM Win32_Process WHERE ProcessID = " & PID)
    procCnt = oProcesses.Count
    If Debugging Then
        WScript.Echo "Processes Count: " & ProcCnt
    End If
    
    If procCnt = 1 Then
        ' Kill the process.
        Set shell = WScript.CreateObject("WScript.Shell")
        shell.Run "TaskKill /F /PID " & PID
    End If
    
    Set oWMI = Nothing: Set oProcesses = Nothing: Set shell = Nothing