Question:
My powershell profile has a custom powershell prompt that unfortunately causes $lastexitcode values to be lost. For instance, given a powershell script “fail.ps1” with contents “exit 123”, when I run the script, $? is $false while $lastexitcode is 0. If I instead run powershell without loading my profile with the custom prompt, after running fail.ps1 then $lastexitcode is 123.
Has anyone seen this problem before? Is there a way to preserve $lastexitcode as the prompt is generated?
I ran into this when using Posh-git, https://github.com/dahlbyk/posh-git, a nice powershell prompt for git.
Answer:
Issue can be resolved by capturing $LASTEXITCODE
at the start of the prompt and restoring it at the end:
1 2 3 4 5 6 7 8 |
function prompt { $realLASTEXITCODE = $LASTEXITCODE # ... $LASTEXITCODE = $realLASTEXITCODE } |