How to Kill Running Process from a specific folder via Batch File

Bill picture Bill · Mar 21, 2016 · Viewed 9.9k times · Source

I am writing an uninstaller batch file and it occasionally fails to delete folders because of running process. Is there a way to kill all running process that reside in a particular folder. Keep in mind that there could be multiple process running from subfolders within the main. So I think it needs to search the running processes and forcefully and silently kill all that reside within "C:\Program Files\PTC" or a subfolder within.

I do know how to kill off a specific process using the "Taskkill" command, but searching for all process running within a folder and killing them all off is a little over my head.

Thanks for the help in advance.

Bill

Answer

npocmaka picture npocmaka · Mar 22, 2016

The way with you'll get the most comprehensive information about a process with batch file will be the WMIC command. Though it does not contain a working directory so probably you'll have to orient yourself by the command line. Check the comments in the script bellow.First replace the workdir variable with your desired path and if the process looks ok uncomment the last line.You can precise:

@echo off

:: Put the work dir here
set "workdir=C:\Windows\system32"
set "workdir=%workdir:\=\\%"

setlocal enableDelayedExpansion
for /f "usebackq tokens=* delims=" %%a in (`
    wmic process  where 'CommandLine like "%%!workdir!%%" and not CommandLine like "%%RuntimeBroker%%"'   get CommandLine^,ProcessId  /format:value
`) do (
    for /f "tokens=* delims=" %%# in ("%%a")  do (
        if "%%#" neq "" (
            echo %%#
            set "%%#"
        )
    )
)

rem if the echoed process looks ok unocment line bellow

rem taskkill /pid %ProcessID% /f

the %% is the wildcard in the wmic query so you can precise the selection more. Pay attention that the second part is not like (and is just for example). Here's more about WQL