1
votes

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

1
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
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

1 Answers

2
votes

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%