Custom powershell prompt is clearing $lastexitcode

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:

Source:

Custom powershell prompt is clearing $lastexitcode by licensed under CC BY-SA | With most appropriate answer!

Leave a Reply