Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom powershell prompt is clearing $lastexitcode

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.

like image 375
Frank Schwieterman Avatar asked May 16 '11 06:05

Frank Schwieterman


2 Answers

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
 }
like image 107
dahlbyk Avatar answered Sep 20 '22 12:09

dahlbyk


You need to do this to make it work:

function prompt {
    $realLASTEXITCODE = $global:LASTEXITCODE

    # ...

    $global:LASTEXITCODE = $realLASTEXITCODE
    # cleanup
    Remove-Variable realLASTEXITCODE
 }
like image 39
sba923 Avatar answered Sep 21 '22 12:09

sba923