Windows – How to tell which “explorer.exe” process is the main one

batch fileprocesswindowswindows-explorer

I have a batch file that changes a few registry files, and then restarts explorer.exe so that they take effect. I'm using the commands

taskkill /f /im explorer.exe
explorer.exe

This of course kills all the explorer.exe processes, including the explorer windows I have open.
(Obviously, I am using the option to Launch folder windows in a separate process.)

Is there any way I can determine which instance of explorer.exe is the main one, and just kill that?

Best Answer

Window title based approach

@techie007 suggested killing the explorer.exe with window title N/A.

Command

for /f "tokens=2,10" %%p in ('tasklist /nh /v /fi "imagename eq explorer.exe"') do if "%%q"=="N/A" taskkill /f /pid %%p

How it works

  • tasklist /nh /v /fi "imagename eq explorer.exe" verbosely lists all processes with image name explorer.exe.

  • for /f "tokens=2,10" %%p in ('COMMAND1') do COMMAND2

    executes COMMAND1. For each line of output, it sets the variables %%p and %%q to the second and tenth "token" (delimited by space) and executes COMMAND2.

    In the case of taskkill /v, %%p now holds the PID and %%q the (beginning of) the window title.

  • if "%%q"=="N/A" taskkill /f /pid %%p checks if the window title is N/A.

    If so, it terminates the process with taskkill.

Memory usage based approach

@Syntech pointed out that this is unreliable for Windows Explorer, but in programs, the main process has always the highest memory usage.

Command

for /f "tokens=2" %%p in ('tasklist /nh /fi "imagename eq explorer.exe" ^| sort /+65') do @set explorerpid=%%p
taskkill /f /pid %explorerpid%

How it works

  • tasklist /nh /fi "imagename eq explorer.exe" lists all processes with image name explorer.exe.

  • sort /+65 sorts the previous output starting with the 65th character (where mem usage begins).

  • for /f "tokens=2" %%p in ('COMMAND') do @set explorerpid=%%p sets explorerpid to the second (tokens=2) input – delimited by spaces – of each line of the output of COMMAND, which is the corresponding PID.

  • Since tasklist's ouput has been sorted, explorerpid holds the claimed PID, and taskkill terminates the process.