0

If a .ps1 script simply runs one tool, the tool's exit code effectively propagates to the caller, which might be another ps1 script or the shell. It can cause CI's to fail (which is good).

But if a .ps1 script wants to run two tools, and ultimately return the failing exit code if either script fails, how to do this? Running the second tool after the first one fails obliterates $LASTEXITCODE from the first and 'passes' in CI.

Even if directly after the running the first tool, I add this:

    if ($LASTEXITCODE -ne 0) {
        exit 4
    }

The script exits, but $LASTEXITCODE still equals 0.

Some other techniques I've found have the very negative side effect of terminating that powershell.exe process with the exit code, but I don't want to force terminating the user's shell when the ps1 script was run directly by the user, or if my ps1 script was invoked from another ps1 script, I don't want to terminate the caller. I just want to set the exit code.

Is there no way to accomplish this in PowerShell?

1
  • 2
    Are you telling, that executing powershell -command "exit 27" and checking $LASTEXITCODE afterwards, does not show 27? Commented Jul 3, 2020 at 15:15

1 Answer 1

2

Andrew,

You need to save the codes:

& ".\Test\Test-Exit27.ps1"
$Exit27 =  $LASTEXITCODE

& ".\Test\Test-Exit4.ps1"
$Exit4 = $LASTEXITCODE

"Results:`n Exit27 = $Exit27`n Exit4 = $Exit4"

Each of the .ps1 files called contains a single line Exit #, e.g. Exit 27.

Results:

Results:
 Exit27 = 27
 Exit4 = 4

HTH

Sign up to request clarification or add additional context in comments.

5 Comments

No go. A ps1 script with exit 27 does not even set $LASTEXITCODE, which remains 0 after the script executes. And capturing the $LASTEXITCODE within the script is pointless if the script itself still returns 0.
How very strange. It does work as you say, in a clean Windows PowerShell or PowerShell Core environment, but not in the VS Dev2019 PowerShell prompt
Oh, it wasn't the VS PowerShell prompt... it's Posh-Git! When I'm in a git repo, the $LASTEXITCODE is cleared by the prompt function itself. Thanks for insisting this worked. :) I'll take it up with the Posh-Git folks.
I guess posh-git had that bug but fixed it a long time ago. In fact from my powershell profile script it is Set-Theme Paradox that is responsible. If I comment that out, it works.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.