Set the text color in PowerShell

14k Views Asked by At

I'm trying to customize the terminal window of my PS (5.1.18362.752). Using the Properties menu and Colors tab, I have set the main background and the printed text as I wish. The colors of errors and warnings are set using a script (following this blog).

$hostGui = $Host.UI.RawUI
$colors = $Host.PrivateData

$hostGui.WindowTitle = "Powerify!"
$hostGui.backgroundcolor = "magenta"
$hostGui.foregroundcolor = "green"

$colors.verbosebackgroundcolor = "magenta"
$colors.verboseforegroundcolor = "green"
$colors.warningbackgroundcolor = "magenta"
$colors.warningforegroundcolor = "green"
$colors.ErrorBackgroundColor = "magenta"
$colors.ErrorForegroundColor = "green"

Further, I also manipulate the prompt's color using the following script (following this answer and coloring strategy in the docs).

function prompt {
  $foreRgb = "15;15;15"
  $backRgb = "240;240;240"
  $style = [char]27 + "[38;2;" + $foreRgb + ";48;2;" + $backRgb + "m"
  ...
  $prompt = $style + $whatever + "> "
  Write-Host $prompt -nonewline
  return " "
}

All the above works, as far I can tell from the screen. However, what I don't get to work is the actual text that the user types in after the prompt, i.e. the command itself. The first word typed in is yellow and the following ones are bright green (or dark green if it's a string), while CTRL+C is displayed in red. While I understand that it's the formatting for the main command and the parameters.

I haven't found any information on how to control those colors, despite it being suggested that it's supposed to be possible (according to this blog).

Most preferably, I'd like to set them from the script but a menu setting will do too. Worst case, I can also live with a registry hack but that's the last resort.

2

There are 2 best solutions below

5
On BEST ANSWER

I think what you want is Set-PSReadLineOption? It specifies the colors of the commands that you type in the prompt.

The Set-PSReadLineOption cmdlet customizes the behavior of the PSReadLine module when you're editing the command line.

You can set it via script or put it in your $profile.

As an example, here's my "theme":

Set-PSReadlineOption -Colors @{
    Type = "DarkCyan"
    Member = "Gray"
    String = "DarkGray"
    Number = "Yellow"
    Comment = "DarkGreen"
    Command = "Cyan"
    Keyword = "Cyan"
    Operator = "Gray"
    Variable = "Magenta"
    Parameter = "Gray"
}
0
On

You can use something like this:

Set-PSReadLineOption -Colors @{
    "Parameter"="#ff81f7"
    "Command"="Blue"
    "Error"=[ConsoleColor]::DarkRed
}

Source: This SuperUser answer