Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get PID from command line filtered by username and imagename

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 one is compUser. Is there a way that I can grab the PID of the compUser cmd.exe?

Edit: This needs further explanation. I'm doing this from a batch file. One of the calls that I'm making in my batch file starts a cmd.exe that never dies. So killing that cmd.exe would be simple:

taskkill /F /IM cmd.exe /FI "username eq compUser"

The problem is that the batch file that I'm in is being handled by another instance of cmd.exe under the username compUser. What I'm attempting to do is get the PID from the original cmd.exe before I start the second cmd.exe. That way I can just use the command:

taskkill /F /IM cmd.exe /FI "username eq compUser" /FI "PID neq [orignal task's PID]"
like image 427
NOTACAT Studio Avatar asked Dec 21 '22 05:12

NOTACAT Studio


2 Answers

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.

like image 186
NOTACAT Studio Avatar answered Jan 12 '23 06:01

NOTACAT Studio


This will display all processes named "cmd.exe" for the user "compUser":

tasklist /FI "IMAGENAME eq cmd.exe" /FI "USERNAME eq compUser"
like image 27
telenachos Avatar answered Jan 12 '23 05:01

telenachos