I suggest using the following code:
@echo off
setlocal EnableExtensions DisableDelayedExpansion
set "LoopCount=6"
set "ForceKill="
:EndProgramLoop
%SystemRoot%\System32\tasklist.exe /NH /FI "IMAGENAME eq LearnBatV1.0.0.exe" | %SystemRoot%\System32\find.exe /I "LearnBatV1.0.0.exe" >nul || goto StartProgram
set /A LoopCount-=1
if %LoopCount% == 0 (
echo ERROR: Failed to terminate LearnBatV1.0.0.exe!
echo/
pause
goto EndBatch
)
if %LoopCount% == 1 set "ForceKill=/F "
%SystemRoot%\System32\taskkill.exe /IM LearnBatV1.0.0.exe %ForceKill%>nul 2>nul
%SystemRoot%\System32\timeout.exe /T 1 /NOBREAK >nul
goto EndProgramLoop
:StartProgram
start "" "K:\POST\Govind\My Actual Work\LearnBat\LearnBatV1.0.0.exe"
:EndBatch
endlocal
The batch file checks first if LearnBatV1.0.0.exe
is running at all. It starts the executable if that is not the case.
The first argument string enclosed in "
is interpreted as title string for the console window even if the started executable is a Windows GUI window and so no console window is opened at all. For that reason ""
is used to define an empty title string. The fully qualified file name of the executable is enclosed in "
as required because of the space character, too. I recommend to use a meaningful title string if the executable is a Windows GUI application.
I hope, your program is coded to work with any directory as current directory as the current directory for LearnBatV1.0.0.exe
is defined by the process starting cmd.exe
to process this batch file and can be any directory for that reason.
But if LearnBatV1.0.0.exe
is really running, there is first decremented by one an environment variable counting how often the loop to end the program is executed already with leaving the loop with an error message if it is not possible to get LearnBatV1.0.0.exe
either gracefully self-terminated or finally brutally killed by the operating system.
There is tried four times to send the WM_CLOSE message via TASKKILL to all the running processes LearnBatV1.0.0.exe
which should result in a graceful self-termination of the executable on not being very bad coded. There is used finally the option /F
to force a brutal kill of the process by the operating system as last attempt.
There is made a delay of one second between each TASKKILL and TASKLIST execution to give the process the time it perhaps needs to gracefully terminate itself.
To understand the commands used and how they work, open a command prompt window, execute there the following commands, and read the displayed help pages for each command, entirely and carefully.
echo /?
endlocal /?
find /?
goto /?
pause /?
set /?
setlocal /?
start /?
taskkill /?
tasklist /?
timeout /?
See also the Microsoft documentation about Using command redirection operators for an explanation of |
and >nul
and 2>nul
and single line with multiple commands using Windows batch file for an explanation of conditional execution operator ||
.