在 PowerShell 中设置文本颜色

Set the text color in PowerShell

我正在尝试自定义 PS (5.1.18362.752) 的终端 window。使用“属性”菜单和“颜色”选项卡,我根据需要设置了主背景和打印文本。错误和警告的颜色是使用脚本设置的(在 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"

此外,我还使用以下脚本(在 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 " "
}

以上所有 有效 ,据我从屏幕上可以看出。但是,我没有开始工作的是用户在提示后输入的实际文本,即命令本身。输入的第一个单词是黄色,后面的单词是亮绿色(如果是字符串,则为深绿色),而 CTRL+C 显示为红色。虽然我知道这是主要命令和参数的格式。

我还没有找到任何关于如何控制这些颜色的信息,尽管有人建议它应该是可能的(根据 this blog)。

最理想的情况是,我想从脚本中设置它们,但菜单设置也可以。最坏的情况,我也可以接受注册表黑客攻击,但这是最后的手段。

我想你想要的是Set-PSReadLineOption?它指定您在提示中键入的命令的颜色。

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

您可以通过脚本设置或将其放入您的$profile

例如,这是我的“主题”:

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

你可以这样使用:

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

来源:这个SuperUser回答