0
votes

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
Are you telling, that executing powershell -command "exit 27" and checking $LASTEXITCODE afterwards, does not show 27?stackprotector

1 Answers

2
votes

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