how to get PID from command line filtered by usern

2019-01-15 11:01发布

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]"

4条回答
神经病院院长
2楼-- · 2019-01-15 11:07

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.

查看更多
【Aperson】
3楼-- · 2019-01-15 11:11

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
查看更多
Juvenile、少年°
4楼-- · 2019-01-15 11:24

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.

查看更多
Root(大扎)
5楼-- · 2019-01-15 11:31

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

tasklist /FI "IMAGENAME eq cmd.exe" /FI "USERNAME eq compUser"
查看更多
登录 后发表回答