Batch script to call executable and exit if it hangs

家住魔仙堡 提交于 2019-12-08 11:53:01

问题


So I need to write a batch script that starts an executable and exits the script as soon as the executable finishes (so no ip pinging wait scripts) but will automatically kill the exe and exit the script after 30 minutes if the executable is still running (hung, not responding, etc)

Here is what I have so far. The find statement correctly outputs the number of processes that match, but my problem is that the ERRORLEVEL always returns 0, regardless of whether or not there are matching executables running.

I am fairly new to batch scripting, so it is very possible I am overlooking some really simple thing.

@echo off
start calc.exe

REM loop 600 times, each loop being 3 seconds (30 minutes total)
FOR /L %%A IN (1,1,600) DO (

   REM find the running executable
   tasklist | find /I /C "calc.exe" > nul
   echo %ERRORLEVEL%

   Rem exit the script if no executable is found (i.e it has run successfully)
   if %ERRORLEVEL% eq 1 EXIT 

   Rem pause for 3 seconds
   ping 1.1.1.1 -n 1 -w 3000 > nul
)

REM kill executable if we haven't exited yet
taskkill /f /im calc.exe

Thanks in advance!


回答1:


in a code block you need always delayed expansion:

@echo OFF &SETLOCAL ENABLEDELAYEDEXPANSION 
start calc.exe

REM loop 600 times, each loop being 3 seconds (30 minutes total)
FOR /L %%A IN (1,1,600) DO (

   REM find the running executable
   tasklist | find /I /C "calc.exe" > nul
   echo !ERRORLEVEL!

   Rem exit the script if no executable is found (i.e it has run successfully)
   if !ERRORLEVEL! eq 1 EXIT 

   Rem pause for 3 seconds
   ping 1.1.1.1 -n 1 -w 3000 > nul
)

REM kill executable if we haven't exited yet
taskkill /f /im calc.exe



回答2:


Change your batch script call to tasklist and find somewhat:

tasklist /FI "IMAGENAME eq calc.exe" | find /I "calc.exe" > nul

This works correctly if I test both with and without a copy of Calculator running (Win7 64 in a command window).



来源:https://stackoverflow.com/questions/17284101/batch-script-to-call-executable-and-exit-if-it-hangs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!