views:

1470

answers:

2

Hello,

Has anyone used taskkill on Win XP in an if condition? I want to use it as a watchdog to restart a program in case it leaks memory and grows too big by adding it in an unending loop.

For example with the following command I can kill Internet Explorer if its memory usage is greater than 40kb (will happen every time):

taskkill /f /fi "imagename eq iexplore.exe" /fi "memusage gt 40" 

What I want to do now is something like this:

set MY_COMM=taskkill /f /fi "imagename eq iexplore.exe" /fi "memusage gt 40" 
if %MY_COMM% equ 0 ( "C:\Program Files\Internet Explorer\IEXPLORE.EXE" ) else ( echo no internet explorer found  )

TIA, Bert

A: 

What exactly are you trying to accomplish with those two lines?

taskkill will kill IE considering the specified criteria are met. The return value can't be assigned in the way you try it, though.

From what I see I am guessing that you are trying to kill IE and afterwards look whether an instance was killed and restart it in this case. Unfortunately the return value from taskkill is 0 in both cases we're having here: criteria met or not met (the return value is 128 if the image name is invalid, though). So we need a little trickery to know whether a process indeed was killed:

taskkill /f /im iexplore.exe /fi "memusage gt 40" 2>NUL | findstr SUCCESS >NUL

By piping into findstr, searching for "SUCCESS" we can determine whether a process actually was killed. The error level is 1 in case the string wasn't found in the output and 0 otherwise. So you can continue as follows:

if errorlevel 1 ( echo No Internet Explorer was killed ) else ( "%ProgramFiles%\Internet Explorer\iexplore.exe" )
Joey
A: 

Hello,

Thank you, you certainly pointed me on the riight track. The first line was not working for me, as errorlevel was always one. The reason is that the precise output of taskkill varies from machine to machine, it will vary depending on language.

On my machine (FR language), in the situation where taskkill kills a process, it will indicate the PID number that was killed. So keeping in mind that one should check on his own version of Windows what the taskkill message is, my complete final code looks like this :

taskkill /f /im iexplore.exe /fi "memusage gt 40" | findstr PID >NUL
if errorlevel 1 ( echo No Internet Explorer was killed ) else ( start "" "C:\Program Files\Internet Explorer\IEXPLORE.EXE" )

Thanks much! Bert