0

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?

Gerhard
  • 22,678
  • 7
  • 27
  • 43
Matt_4
  • 147
  • 1
  • 12
  • 2
    You can go with powershell, see [this](https://stackoverflow.com/questions/4762982/powershell-get-process-id-of-called-application). – Zilog80 May 04 '21 at 13:39

2 Answers2

1

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.

Gerhard
  • 22,678
  • 7
  • 27
  • 43
0

You could also use to both run, and kill, your file too.

For example:

@For /F "Tokens=3 Delims=; " %%G In ('%SystemRoot%\System32\wbem\WMIC.exe
 Process Call Create "T:\he\Absolute Path\To\My File\myexe.exe"
 2^>NUL ^| %SystemRoot%\System32\find.exe "Id = "') Do @Set "PID=%%G"
@%SystemRoot%\System32\timeout.exe /T 60 /NoBreak >NUL
@%SystemRoot%\System32\wbem\WMIC.exe Process Where "ProcessId='%PID%'" Call^
 Terminate >NUL 2>&1

If you don't mind long lines, you dont need to split them for readability:

@For /F "Tokens=3 Delims=; " %%G In ('%SystemRoot%\System32\wbem\WMIC.exe Process Call Create "T:\he\Absolute Path\To\My File\myexe.exe" 2^>NUL ^| %SystemRoot%\System32\find.exe "Id = "') Do @Set "PID=%%G"
@%SystemRoot%\System32\timeout.exe /T 60 /NoBreak >NUL
@%SystemRoot%\System32\wbem\WMIC.exe Process Where "ProcessId='%PID%'" Call Terminate >NUL 2>&1
Compo
  • 36,585
  • 5
  • 27
  • 39