Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dot-sourcing PowerShell script file and return code

Tags:

powershell

Here's some PowerShell code:

test.ps1:

. C:\path\to\test2.ps1
exit 5

test2.ps1:

exit 7

Run test.ps1 from a standard command prompt however you like to run PowerShell scripts, then call:

echo %errorlevel%

The expected result is a return code of 7. This is the first exit command in the PowerShell script. The actual result, however, is a return code of 5. Obviously the included script was terminated but its return code was ignored and the calling script happily continued.

How can I really terminate a script and return a result code no matter how it was called?

Or alternatively, how should I call test2.ps1 so that its return code is passed on to the outside world?

Background: My build script is made with PowerShell and it includes module files for different tasks. One task currently fails and the build server didn't detect the error because my start build script still returned 0.

like image 943
ygoe Avatar asked Jul 17 '15 12:07

ygoe


1 Answers

You should query $lastExitCode that would have nonzero value if the last script/program exited with failure. So, your sample's test1.ps1 should be like this:

. C:\path\to\test2.ps1
if ($lastexitcode -ne 0) { exit $lastexitcode} 
exit 5
like image 143
Vesper Avatar answered Sep 25 '22 22:09

Vesper