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 titleN/A
.Command
How it works
tasklist /nh /v /fi "imagename eq explorer.exe"
verbosely lists all processes with image nameexplorer.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 executesCOMMAND2
.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 isN/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
How it works
tasklist /nh /fi "imagename eq explorer.exe"
lists all processes with image nameexplorer.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
setsexplorerpid
to the second (tokens=2
) input – delimited by spaces – of each line of the output ofCOMMAND
, which is the corresponding PID.Since
tasklist
's ouput has been sorted,explorerpid
holds the claimed PID, andtaskkill
terminates the process.