I need to be able to get the PID from a running process (cmd.exe) using the command line. The problem is there are two cmd.exe running. One is under the username SYSTEM and
The way I ended up having to do this was use:
TASKLIST /NH /FI "IMAGENAME eq cmd.exe" /FI "username eq compUser"> psid.txt
FOR /F "tokens=2" %%I in (psid.txt ) DO set pIdNotToKill=%%I
right before I started the batch script that hangs. Then when I was ready to kill the hanging cmd window:
taskkill /F /IM cmd.exe /FI "PID ne %pIdNotToKill%" /FI "username eq compUser"
There is probably a better way, but this worked.
This will display all processes named "cmd.exe" for the user "compUser":
tasklist /FI "IMAGENAME eq cmd.exe" /FI "USERNAME eq compUser"
I set the Title to my own cmd window, other cmd windows what I call or run by "start /b" I rename to other window title name. Next I detect PID, set MYPID and kill all other cmd with OTHER PID of my.
All on one file, working in other label loop with timeout dalay.
@(@Title TitleOfMyScript)
for /f "tokens=2" %%a in ('tasklist /fi "imagename eq cmd.exe" /fi "windowtitle eq TitleOfMyScript" /nh') do set MYPID=%%a
taskkill /FI "PID ne %MYPID%" /FI "IMAGENAME eq cmd.exe" /F
I'd like just to share my piece of code, maybe it will be useful for somebody. It is based on the comment from jiggawagga, but it can terminate many processes:
@ECHO off
SETLOCAL ENABLEDELAYEDEXPANSION
REM kill old server process
SET pIdNotToKill=
SET pIdFilter=
FOR /F "tokens=2" %%I IN (%SERVER_HOME%\psid.txt) DO (
IF NOT "%%I"=="No" (
SET pIdNotToKill=!pIdNotToKill! %%I
SET pIdFilter=!pIdFilter! /FI "PID ne %%I"
)
)
IF NOT "!pIdNotToKill!"=="" (
ECHO Killing all Java processes except%pIdNotToKill%
ECHO TASKKILL command will be called with the filter%pIdFilter%
TASKKILL /F /IM java.exe %pIdFilter%
)
DEL %SERVER_HOME%\psid.txt
TASKLIST /NH /FI "IMAGENAME eq java.exe" > %SERVER_HOME%\psid.txt
right before I start server process.