user2726975
user2726975

Reputation: 1353

batch file error handling after calling C# program

I have a batch file that calls C# program. This C# program makes call to SQL Server database. Sometimes it is unable to connect to the database and the exception handler prints stack trace and exits c# program. I want to try to run this program maximum of 5 times. If it succeeds (before 5 tries) then go to next step (CheckStatus) else Error out and quit.

When I run this, It is printing %ERRORLEVEL% as zero even when C# program has an error.

@ECHO OFF

SET Header=-----------------------------------------------------
SET Logfile=C:\LOG\log.txt
set %ERRORLEVEL% = 0

echo %header%
ECHO Running the batch file >> %Logfile%

if '%1' == '' goto usage
if '%2' == '' goto usage
if '%1' == '/?' goto usage
if '%1' == '-?' goto usage
if '%1' == '?' goto usage
if '%1' == '/help' goto usage


SET SQLServer=dbsql\production
SET SQLUser=user1
SET SQLPass=pwd1
SET SQLCommandMaster=osql -S%SQLServer% -n -U%SQLUser% -P%SQLPass% -b -i


GOTO %1%
:Start
Set count=0

:RunCSharpProgram
set /a count+=1
ECHO starting RunCSharpProgram count >> %Logfile%
timeout /t 10
SET RunningStep="RunCSharpProgram"
start "" "C:\CSharpProject\GetData\GetData\bin\Debug\GetData.exe"
ECHO %ERRORLEVEL% >> %Logfile%
IF %ERRORLEVEL% ==1 and count LEQ 5 (GOTO RunCSharpProgram)
IF %ERRORLEVEL% ==1 and count EQ 5 (GOTO error)
IF %ERRORLEVEL% ==0 (GOTO CheckStatus)

:CheckStatus
ECHO Check Status of tables >> %Logfile%
REM %SQLCOMMANDMASTER% /Q "EXEC TestDB.dbo.CheckStatus"
goto end

:usage
echo Usage: %0  'start step' 'end step'
goto end

:error
REM ---------------------------------------------------------------------
ECHO ERROR RUNNING BatchFileTest.BAT >> %Logfile%


:end
echo %header% >> %Logfile%
echo END >> %Logfile%

Not sure what is wrong with this batch file. Thanks MR

Upvotes: 1

Views: 478

Answers (1)

Subbu
Subbu

Reputation: 2205

When you use start, it would start a new shell to run your program.

Official documentation

Starts a separate Command Prompt window to run a specified program or command.

Since it is a separate command prompt you will NOT get back the error codes. So, simple solution do not use the start

instead of

start "" "C:\CSharpProject\GetData\GetData\bin\Debug\GetData.exe"

you can just use

"C:\CSharpProject\GetData\GetData\bin\Debug\GetData.exe"

Upvotes: 3

Related Questions