Windows – Pass PIDs from tasklist and kill processes with tasklist WITH spaces in the name of the process

batchbatch-fileprocesswindows

So this question is VERY similar to this question, with this answer. But some of my processes have a space in the name, and CMD returns nothing. My original question has been answered in this answer, this question is asking how would I do this, but with spaces in the process name.

Code so far:

FOR /F "usebackq tokens=1-10" %%i IN (`tasklist ^|findstr /b "nvsphelper64.exe"`) DO taskkill /F /PID %%j
FOR /F "usebackq tokens=1-10" %%i IN (`tasklist ^|findstr /b "nvcontainer.exe"`) DO taskkill /F /PID %%j
FOR /F "usebackq tokens=1-10" %%i IN (`tasklist ^|findstr /b "NVIDIA Share.exe"`) DO taskkill /F /PID %%j
pause

I already tried putting ' around NVIDIA Share.exe, and I also tried putting " around it as well, but it still ignores that line when executing.

(I have tried executing as a 32bit exe as admin, and as batch as admin and without admin, but to no avail.)

Best Answer

There seem to be some misunderstandings how for /f works in combination with normal tasklist output and findstr.

> tasklist

Image Name                     PID Session Name        Session#    Mem Usage
========================= ======== ================ =========== ============
System Idle Process              0 Services                   0          8 K
System                           4 Services                   0      4.896 K
...snip...

The default For /f delimiter is the space and you don't change that.
Consecutive delimiters are counted as one and leading ones are ignored.
So to get the PID in the line System Idle Process you have to address token 4, in the next line System the PID is token 2.

Findstr OTOH works in RegEx mode by default which means the search words seperated by space are ORed - each one matches independently. To overcome this either exchange the space between NVIDIA Share.exe with a dot meaning any character - or switch to /C:"NVIDIA Share.exe" to match literally. (to exactly match a literal dot in RegEx you have to escape it with a backslash.

So this should work for you:

FOR /F "tokens=2" %%A IN ('tasklist ^|findstr /b "nvsphelper64\.exe" ') DO taskkill /F /PID %%A
FOR /F "tokens=2" %%A IN ('tasklist ^|findstr /b "nvcontainer\.exe"  ') DO taskkill /F /PID %%A
FOR /F "tokens=3" %%A IN ('tasklist ^|findstr /b "NVIDIA.Share\.exe" ') DO taskkill /F /PID %%A
pause