Friday, December 29, 2023

Windows batch file to run an exe and check its result

Windows batch file to run an exe and check its result. If you get the strange ") was unexpected at this time" error when you run it, try adding a comment line before that ")", it usually fixes it (and use "rem" instead of "::"). If you get "3 was unexpected at this time", move inner for loop out of the nested loop:

::Test pass criteria: Exe has to finish within maxExeRunTime_s and exe output's last line must be equal to expectedLastLine
@echo off
setlocal enabledelayedexpansion
set currentDir=%CD%
:: Set variables
set secondWindowTitle=My second window
set exeName=MyExe.exe
set exeFolder=x64/Release
set maxExeRunTime_s=5
set tempOutFile=temp_output.txt
set expectedLastLine=Simulation completed.
cd %exeFolder%
:: Start the program in a new window and redirect output to a file
start "%secondWindowTitle%" cmd /c %exeName% > %tempOutFile%
:: Allow the program some time to run
timeout /t %maxExeRunTime_s%
:: Check if the program window is still open
tasklist /FI "WINDOWTITLE eq %secondWindowTitle%" | find "%exeName%" > NUL
:: If task has finished, the above tasklist command will fail and errorlevel will be 1
if %errorlevel%==1 (
echo %exeName% finished within %maxExeRunTime_s% seconds.
echo Get the last line from %tempOutFile%...
for /F "delims=" %%i in ('type %tempOutFile%) do set lastLine=%%i
:: Extract only the text part from the last line
set "lastLine=%lastLine:*]=%"
echo Last line is "%lastLine%"
echo expected: "%expectedLastLine%"
if "%lastLine%"=="%expectedLastLine%" (
echo The last line was as expected.
) else (
echo The last line was different!
)
del %tempOutFile%
) else (
echo %exeName% exceeded max run time of %maxExeRunTime_s% seconds.
taskkill /FI "WINDOWTITLE eq %secondWindowTitle%"
)
:: Return to the original directory
cd %currentDir%
view raw runAndCheck.bat hosted with ❤ by GitHub

No comments:

Post a Comment