Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

syntax for testing TASKKILL's errorlevel

What is the correct syntax for testing the errorlevel of TASKKILL in the context of the batch file shown below?

:Launch
   start "CloseMe" "C:\Program Files\internet explorer\iexplore.exe" "file://C:\ProgramData\Schneider Electric\Citect SCADA 2016\User\1173051_SM_STP\Files\Stony Mountain Institute Lift Station.html"
   TIMEOUT 1 & 
:ShiftFocus
   wscript "C:\ProgramData\Schneider Electric\Citect SCADA 2016\User\1173051_SM_STP\Files\SendAltTab.vbs"
   TASKKILL /IM iexplore.exe /FI "WINDOWTITLE eq CloseMe - Internet Explorer"
   if %errorlevel% == 1 GOTO ShiftFocus
:End
exit

I'm trying to get my batch file to run TASKKILL then test the result.

If the result is "INFO: No tasks running with the specified criteria." I need the batch file to try TASKKILL again.

If the result is "SUCCESS: Sent termination signal to ... ." I need the batch file to close.

To accomplish this I'm using if statements, labels and gotos which I learned about here and here.

I'm suspect I'm using errorlevel incorrectly because no matter what TASKKILL does its errorlevel, from my batch files perspective, is 0. Some answers to similar posts are using %errorlevel% and others are using errorlevel. No matter which I use in my batch file its sees an error level of 0 regardless of the actual result of TASKKILL.

like image 983
mike_yung Avatar asked Dec 04 '25 23:12

mike_yung


1 Answers

The taskkill clears ErrorLevel when you have provided a filter /FI which results in no match! However, when you only filter for image names (/IM) or process IDs (/PID), ErrorLevel becomes set to 128 if no matches have been encountered.

Therefore I would prefilter the processes by tasklist and use taskkill together with its /PID filter:

:LOOP
rem // Establish a short wait time to not heavily load the processor:
> nul timeout /T 1 /NOBREAK
rem // Prefilter processes and retrieve the PID of the applicable one:
set "PID=" & for /F "tokens=1* delims=:" %%T in ('
    tasklist /FI "IMAGENAME eq iexplore.exe" /FI "WINDOWTITLE eq CloseMe - Internet Explorer" /FO LIST
') do if "%%T"=="PID" for /F %%W in ("%%U") do set "PID=%%W"
rem // Loop back in case no PID could be retrieved:
if not defined PID goto :LOOP
rem // Try to kill the task and loop back in case of failure:
taskkill /PID %PID% || goto :LOOP
like image 168
aschipfl Avatar answered Dec 06 '25 16:12

aschipfl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!