How to colorize the Powershell prompt?

screenshot of coloured prompt

PowerShell prompts

What you want to do is customise the prompt.

The default prompt in PowerShell 3.0 and newer is:

function prompt  
{  
    "PS $($executionContext.SessionState.Path.CurrentLocation)$('>' * ($nestedPromptLevel + 1)) "  
}

Colour escape sequences

Now, Windows 10 supports the ANSI escape codes in its conhost, and 24-bit colour is supported since 1703.

To use one of the ANSI escape codes, we need a literal ESC character. This is octal 033, or decimal 27. In Bash, you would use "\033" or "\e"; There's no direct equivalent sequence in PowerShell but you can instead embed an expression: "$([char]27)"

In PowerShell Core you can use the "`e" escape sequence instead. Thanks to the comment by asherber.


Use in PowerShell

This means you can, for example, use the following escape sequence to set the background colour to cyan with the code 46:

"$([char]27)[46m"

Which can be used like so:

echo "$([char]27)[46mColoured text"

To make things more readable, let's define a variable:

$ESC = [char]27

So we can use:

"$ESC[46m"

Where $ESC is the literal ESC character, [ defines the start of the param list, and m the end.

Using it in a command:

echo "$ESC[46mColoured text"

And to restore the original colour settings, we use the code 0 instead:

echo "$ESC[46mColoured text$ESC[0mUncoloured text"

More advanced colours

If you aren't happy with the basic 16-colour palette, you can use full 24-bit colours with the form:

"$ESC[48;2;<r>;<g>;<b>m"

Where <r> is the decimal value for red from 0-255, <g> for green and <b> for blue, e.g. "$ESC[48;2;255;0;123m"

Please refer to the documentation for more information.

In fact, this is all directly equivalent to what you would do in bash, except you need to use $ESC (after you've defined it) instead of \e or \033.


Setting a coloured prompt

Putting these together, we can use the ANSI colour escape codes in a modified prompt to change the background colour:

function prompt  
{  
    $ESC = [char]27
    "$ESC[46mPS $($executionContext.SessionState.Path.CurrentLocation)$('>' * ($nestedPromptLevel + 1)) $ESC[0m"  
}

Persistence

If you want this to persist across sessions, add it to your profile (like .bashrc). You can view the path to your profile in $profile.