none
Customize powershell prompt to display return code of last command RRS feed

  • Question

  • Displaying $? in the prompt function of $profile always returns "True". How do I make my customized prompt display the status of the command I just ran?

    Thanks!

    Jon

    Thursday, December 4, 2014 4:47 PM

Answers

  • Your write-host commands return true (they succeeded), so $? will always be $true.


    -- Bill Stewart [Bill_Stewart]

    • Marked as answer by Jon Redinger Thursday, December 4, 2014 5:53 PM
    Thursday, December 4, 2014 5:44 PM
    Moderator

All replies

  • What does your prompt function look like?


    -- Bill Stewart [Bill_Stewart]

    Thursday, December 4, 2014 5:29 PM
    Moderator
  • Hi Bill!

    function Prompt {
            write-host ("⌠ ") -nonewline -foregroundcolor green
            write-host ($(get-location)) -foregroundcolor white
    write-host ("| $?") -foregroundcolor green
            write-host ("⌡") -nonewline -foregroundcolor green
            return " "
    }

    So it looks like in integral symbol followed by some read info and an input cursor.

    ⌠ C:\
    | True

       
    Thursday, December 4, 2014 5:34 PM
  • Your write-host commands return true (they succeeded), so $? will always be $true.


    -- Bill Stewart [Bill_Stewart]

    • Marked as answer by Jon Redinger Thursday, December 4, 2014 5:53 PM
    Thursday, December 4, 2014 5:44 PM
    Moderator
  • Thanks, Bill! For some reason, the first time I tried to park the value of $?, it didn't work. I must have done something wrong. Anyway, it does what I want now. Thanks much!

    function Prompt {
    $var=$?
    write-host ("⌠ ") -nonewline -foregroundcolor green
    write-host ($(get-location)) -foregroundcolor white
    write-host ("| $var") -foregroundcolor green
    write-host ("⌡") -nonewline -foregroundcolor green
    return " " 
    }

    Jon

    Thursday, December 4, 2014 5:53 PM
  • To trap the errors of a CmdLet use -ev MyError

    Now that will be the saved last error if one exists.

    Get-Process xxxxx -ev MyError
    $Myerror


    ¯\_(ツ)_/¯

    Thursday, December 4, 2014 7:49 PM