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

Elisabeth
  • 20,496
  • 52
  • 200
  • 321
  • 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. – Matt Nov 20 '15 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. – Elisabeth Nov 20 '15 at 16:16

1 Answers1

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%
Mathias R. Jessen
  • 157,619
  • 12
  • 148
  • 206
  • You are my hero! That gave me 0 for suceess and 1 or -1040304 when the script failed in any way. Thanks Mathias. – Elisabeth Nov 20 '15 at 16:14
  • Is it ok to use the exit /b %ERRORLEVEL% ONE time although when I have multiple for sqlcmd calls? – Elisabeth Nov 20 '15 at 16:21
  • 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 :) – Mathias R. Jessen Nov 20 '15 at 16:26