0

as the title says, I want to kill all backgroundprocess of a certain program, but keep the running foreground program on windows (Server 2016). All the processes are using the same .exe and therefore the only thing to separate them is to check if they are running in background or not. Using tasklist I can see the difference:

Abbildname                     PID Sitzungsname       Sitz.-Nr. Speichernutzung
========================= ======== ================ =========== ===============
BpNexT.exe                    6900 Services                   0       254.936 K
BpNexT.exe                    6164 Console                    1        63.912 K
BpNexT.exe                    6377 Services                   0       251.234 K

The first and last process has to be killed, the second one should keep running. I tried to filter by service, but failed:

taskkill /IM BPNEXT.EXE /FI "services eq Services" /T /F

How do I kill the desired processes?

Jens

  • Parse the tasklist result with `for` and kill by pid – Anders May 12 '22 at 14:10
  • Thanks for the hint. I tried to get the desired line by using: @ECHO OFF setlocal enabledelayedexpansion FOR /f "tokens=*" %%G IN ('tasklist /FO "CSV" ^| findstr /I BPNEXT.EXE ^| findstr Services') DO ( echo %%G ) It worked so far. But now I'm stuck because i can not extract the given PID from the string, i.e. "BpNexT.exe","4852","Services","1","53.764 K". – Jens Körte May 18 '22 at 15:21
  • Another FOR on the result of the first FOR that uses the tokens parameters to extract – Anders May 18 '22 at 16:10

1 Answers1

0
FOR /f "tokens=*" %%G IN ('tasklist ^| findstr /I BPNEXT.EXE ^| findstr Services') DO (
    set /a counter=1
    FOR %%H IN (%%G) DO (
        if !counter! == 2 (
            taskkill /F /PID %%H
        )
    set /a counter=!counter!+1
    )
)