Elisabeth
Elisabeth

Reputation: 21206

powershell $lastexitcode does not work when running batch files

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

Upvotes: 2

Views: 1970

Answers (1)

Mathias R. Jessen
Mathias R. Jessen

Reputation: 174485

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%

Upvotes: 3

Related Questions