Dot-sourcing PowerShell script file and return code

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 line, however you like to run PowerShell scripts and then call:

echo %errorlevel%

      

The expected result is return code 7. This is the first command exit

in the PowerShell script. The actual result, however, is return code 5. Obviously, the included script completed, but its return code was ignored and the script call happily continued.

How can I end the script and return the result code no matter how it was called?

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

Background: My build script is done using PowerShell and includes module files for different tasks. One of the tasks is currently failing and the build server did not encounter an error because my initial link script still returned 0.

+3


source to share


1 answer


You have to ask $lastExitCode

, which would be nonzero if the last script / program ended with an error. So your sample test1.ps1

should look like this:



. C:\path\to\test2.ps1
if ($lastexitcode -ne 0) { exit $lastexitcode} 
exit 5

      

+3


source







All Articles