问题
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