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

后端 未结 4 1359
广开言路
广开言路 2020-12-06 14:45

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

相关标签:
4条回答
  • 2020-12-06 15:01

    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.

    0 讨论(0)
  • 2020-12-06 15:07

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

    tasklist /FI "IMAGENAME eq cmd.exe" /FI "USERNAME eq compUser"
    
    0 讨论(0)
  • 2020-12-06 15: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
    
    0 讨论(0)
  • 2020-12-06 15:17

    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.

    0 讨论(0)
提交回复
热议问题