I am running many exe through multiple batches. Sometimes it happens that some exes got stuck so I chose to kill them after a timeout, like this:
CD mypath
start myexe.exe
timeout 60
TSKILL myexe
However, since all the exe have the same name, the batch does not close the exe it started but all of them. I also tried this:
cd mypath
for /f "tokens=2 delims==; " %%a in ('start myexe^| find "ProcessId" ') do set MyPID=%%a
timeout 60
taskkill /PID %MyPID% /T
but the timeout
starts just once the exe had finished.
How can I kill the process that the specific batch opened after a timeout?
You already got a link to a pure powershell
solution in the comment to your quesiton, but if you want to retain the main batch-file
format, you can incorporate some powershell
into the batch file.
@echo off
pushd "mypath"
for /f %%i in ('powershell "(Start-Process myexe -passthru).ID"') do (
timeout /t 60
taskkill /PID %%i
)
popd
Note I replaced you cd
command with pushd
where later we have to popd
to return to the directory before we used pushd
. I is easier to push to and from directories without having to define the cd
command each time. It is also not concerned about changing drives where cd
requires the /d
switch.