Search code examples
windowsprocesstaskkill

How to kill a background process in windows and keep foreground process running


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


Solution

  • 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
        )
    )