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.
Issue can be resolved by capturing $LASTEXITCODE
at the start of the prompt and restoring it at the end:
function prompt {
$realLASTEXITCODE = $LASTEXITCODE
# ...
$LASTEXITCODE = $realLASTEXITCODE
}
You need to do this to make it work:
function prompt {
$realLASTEXITCODE = $global:LASTEXITCODE
# ...
$global:LASTEXITCODE = $realLASTEXITCODE
# cleanup
Remove-Variable realLASTEXITCODE
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With