@ECHO OFF :: =========================================================================== :: This batch file closes all running instances of a given. :: executable, gracefully at first, then more forcibly. It :: is intended for use with AlwaysUp. :: (http://www.coretechnologies.com/products/AlwaysUp/) :: :: Usage: :: close-application :: where :: is the name of the executable to be closed. :: :: Created by Core Technologies Consulting, LLC :: https://www.coretechnologies.com/ :: =========================================================================== :: Get the name of the executable to be closed, passed as the :: first argument. Must be an exeutable (*.exe). IF [%1] == [] GOTO show-usage SET exe-name=%1 SET extension=%~x1 IF [%extension%] == [] ( SET exe-name=%exe-name%.exe ) ELSE IF /I [%extension%] NEQ [.exe] ( ECHO The executable name must end in ".exe". GOTO show-usage ) :: Session is the second parameter (optional). SET session=%2 :: Get the current session if necessary. IF [%session%] == [current] ( for /f "tokens=4 delims= " %%G in ('tasklist /FI "IMAGENAME eq tasklist.exe" /NH') do SET session=%%G ) :: Reject if there is a session parameter but it's not understood. IF [%session%] NEQ [] (IF 1%session% NEQ +1%session% GOTO show-usage) :: Setup commands based on if there is a session or not. IF [%session%] == [] ( SET check-command=tasklist /nh /fi ^"imagename eq %exe-name%^" ^| find /i ^"%exe-name%^" SET kill-command=taskkill /im ^"%exe-name%^" SET success-message=All copies of %exe-name% were closed ) ELSE ( SET check-command=tasklist /nh /fi ^"imagename eq %exe-name%^" /fi ^"session eq %session%^" ^| find /i ^"%exe-name%^" SET kill-command=taskkill /im ^"%exe-name%^" /fi ^"session eq %session%^" SET success-message=All copies of %exe-name% running in session %session% were closed ) :: Done if the executable is not running %check-command% IF %ERRORLEVEL% EQU 1 GOTO not-running :: It's running. Try to stop it, gracefully. %kill-command% :: Wait for it to go. timeout 2 > nul %check-command% IF %ERRORLEVEL% EQU 1 GOTO closed-gracefully :: Try again, gracefully. %kill-command% :: Wait for it to go peacefully. timeout 3 > nul %check-command% IF %ERRORLEVEL% EQU 1 GOTO closed-gracefully :: OK, it still hasn't closed gracefully. Be more forceful. %kill-command% /f :: Again, wait for it to go. timeout 1 > nul %check-command% IF %ERRORLEVEL% EQU 1 GOTO closed-forcibly :: It's still running! Fail. echo Failed to close %exe-name%! exit /b 1 :show-usage echo Usage: close-application ^[exe-name^] ^ exit /b 2 :closed-forcibly echo %success-message% forcibly. exit /b 0 :closed-gracefully echo %success-message% gracefully. exit /b 0 :not-running IF [%session%] == [] ( echo %exe-name% is not running. ) ELSE ( echo %exe-name% is not running in session %session%. ) exit /b 0