Taskkill for all running processes that exist in a specific directory

2

I basically want to combine the following sets of commands. In other words I need to check to see if any executable that exists in c:\apps is running, and if any are, to kill them. Once these commands are complete, I will do a robocopy to update files in c:\apps. This script will be deployed with SCCM. Because of this, I need all commands to return errorlevel 0, otherwise it will report the deployment as failed.

tasklist 2>NUL | find /I /N "processname.exe">NUL
if "%ERRORLEVEL%"=="0" taskkill /f /im processname.exe

and

for /r c:\apps\ %%G in (*.exe) do taskkill /F /IM %%~nxG

Nathan

Posted 2014-03-13T14:41:40.613

Reputation: 21

2Welcome to SU! What's your question exactly? What problem are you running into while trying to accomplish your stated goal? – Ƭᴇcʜιᴇ007 – 2014-03-13T14:48:41.800

Also, keep in mind that while an executable is called launchme.exe, when in memory the image name might be different. launchme.exe may just be a wrapper to other libraries/executables which need to be loaded before the actual UI is displayed. In other words, don't rely in the executable name alone. – JSanchez – 2014-03-13T15:56:46.163

Ultimately I want to be able to copy some files to the c:\apps folder. In order to do that, the executables that exist in c:\apps all have to be killed off. Good point on the wrappers, but in my case, it's not a concern. Also, sidenote, the reason I want errorcode 0 is so that the deployment in SCCM won't report as "failed". – Nathan – 2014-03-14T20:01:45.600

Answers

1

I propose something such as:

WMIC PROCESS WHERE "ExecutablePath like 'C:\Apps\%%'" DELETE

There's an apostrophe followed directly by quotation marks there, so you may want to just copy and paste that.

So that's just one rather simple line (rather than a batch file).

This is a fairly powerful and flexible technique. So, if that doesn't end up working exactly like what you have in mind, play with it. There's likely to be a property that will be unique to the programs you're seeking to kill. An example for researching the details is available at: taskkill - end tasks with window titles ending with a specific string : TOOGAM's answer which presents a fairly similar scenario.

TOOGAM

Posted 2014-03-13T14:41:40.613

Reputation: 12 651

0

See this batch work for you.

@echo off

pushd c:\apps
FOR %%A IN (*.exe) do (
tasklist /FI "IMAGENAME eq %%A" 2>NUL | find /I /N "%%A">NUL
if "%ERRORLEVEL%"=="0" taskkill /f /im %%A
)

stderr

Posted 2014-03-13T14:41:40.613

Reputation: 9 300

1He included a /R and %%~nxG and what he did there was better. /R looks through subdirectories. and no need for a pushd if you use the for loop header that he had. And if you're going to do a pushd you might want to do a popd. And if he wants the whole thing to end in errorlevel 0, you might want to do something like dir c:\windows >nul at the end. – barlop – 2014-03-14T21:07:32.497