2

I try to get the exitcode/errorlevel code from a bat file into the powershell script calling the bat file.

Althought the %ErrorLevel% is 1:

BAT file

call aCONFIGURATION
for %%f in (.\createData\*.g.sql) do sqlcmd -b -U %UserName% -P %Password% -S %sqlClonedServer% -d %sqlClonedDatabaseName%  -i %%f -r1 1> NUL
echo %ERRORLEVEL%

When I do in the powershellscript

$lastexitcode its ALWAYS 0 but the %ErrorLevel% says 1

$build = "c:\my.bat"
$state = & $build
Write-Host $LASTEXITCODE

I am pulling my hairs of this crap powershell full with bugs.

I have read these links but they did not help as the result is different:

How can I fix the $lastexitcode

2
  • Did you just reask the same question again more of less.... If you disagree with the close reason you have already done what you needed to. You could edit the question to explain why it is not a duplicate. Commented Nov 20, 2015 at 12:50
  • The old question is deleted not because its a duplicate but because its not needed anymore. The new question goes a step further with the info I can present. Commented Nov 20, 2015 at 16:16

1 Answer 1

3

echo %ERRORLEVEL% just writes the error code to stdout, after which the batch file exits normally.

If you want the batch script to actually return an error on exit, use exit /b [exitcode]:

call aCONFIGURATION
for %%f in (.\createData\*.g.sql) do sqlcmd -b -U %UserName% -P %Password% -S %sqlClonedServer% -d %sqlClonedDatabaseName%  -i %%f -r1 1> NUL
exit /b %ERRORLEVEL%
Sign up to request clarification or add additional context in comments.

3 Comments

You are my hero! That gave me 0 for suceess and 1 or -1040304 when the script failed in any way. Thanks Mathias.
Is it ok to use the exit /b %ERRORLEVEL% ONE time although when I have multiple for sqlcmd calls?
Well, the %ERRORLEVEL% will only contain the exit code of the last call (much like $LASTEXITCODE). Whether it's "ok" is 100% dependant on your use case and requirements :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.