Windows – Find process by thread ID

batchprocesswindowswindows 7

One of my programs outputs its thread ID for debugging purposes. For testing reasons I'd like to kill the process to which the thread ID belongs.

How do I get the process ID if I have the thread ID so that I can use it with taskkill?

I tried

  • tasklist but it doesn't seem to have a switch for thead IDs.
  • SysInternals Process Explorer's "Find handle" feature, which works, but I'd need something that can be automated in a batch file
  • SysInternals Handle -a Thread, but that doesn't seem to work. handle -a | find "Thread" works better, but I lose the process information

Best Answer

You can do it like this with a batch file:

Batchfile killprocess.bat:

@echo off
set processhandle=
set description=
set handle=%1
IF "%handle%." == "." (
  echo Usage: killprocess threadID
  exit/b
)

FOR /F "tokens=*" %%A IN ('WMIC PATH Win32_thread WHERE handle^=%handle% GET Processhandle /VALUE ^| find "="') DO set "%%A"
FOR /F "tokens=*" %%A IN ('WMIC PATH Win32_process WHERE handle^=%processhandle% GET Description /VALUE ^| find "="') DO set "%%A"

IF "%ProcessHandle%." == "." (
  echo ThreadID not found
  exit/b
)

echo I'm going to kill %Description% (Processhandle = %processhandle%) if you don't press Q in 5 seconds
echo (or you can press Y to continue)
choice /N /T 5 /C yq /D y
if "%errorlevel%"=="2" goto :eof

echo Killing %Description% (Processhandle = %processhandle%)
Taskkill /PID %processhandle% /T /F

Usage would be something like this:
killprocess 13008

Edit: I also added an abort option (choice) and a description of the process being killed. You could delete this if you don't want it.

Related Question