如何在 Powershell 控制台中为 PSReadLineOption v2 使用 ANSI 转义序列颜色代码?

How to use ANSI escape sequence color codes for PSReadLineOption v2 in Powershell console?

我正在尝试使用 Powershell (v5.1) 的内置 PSReadLine (v2) 模块来自定义 Powershell 控制台文本颜色。

以前版本的 PSReadLine 允许您为任何给定的标记类型简单地指定 -Background-Foreground 参数。但情况已不再如此。 PSReadLine v2 引入了使用 ANSI 转义码来定义颜色行为。我收集到这允许更大的灵活性,但它要完成的任务非常复杂。关于这些代码的文档随处可见,并且高度依赖于宿主应用程序的实现,这使得找到答案变得更加困难。

简单地为文本前景着色(相对)容易,例如:

set-psreadlineoption -colors @{
    CommandColor = "`e[93m"
    CommentColor = "`e[32m"
}

然而,如果您想引入修饰,例如粗体、下划线或我特别感兴趣的背景颜色以及这些的组合,事情就会变得更加复杂。

SelectionColor 的默认值(用不同的背景颜色突出显示选定的文本)是`e[35;43m。但是那个大提示仍然不足以泄露我正在寻找的语法秘密。

doc for Set-PSReadLineOption 非常实事求是地说:

You can specify other escape sequences including:
256 color
24-bit color
Foreground, background, or both
Inverse, bold

...但未提供示例。

您将如何指定转义码来定义前景色和背景色,或任何其他颜色和彩色装饰的组合?

我发现有助于了解这些转义码的资源是: http://jafrog.com/2013/11/23/colors-in-terminal.html https://en.wikipedia.org/wiki/ANSI_escape_code#SGR_parameters

但我无法完全理解这些。

已解决:

感谢@LotPings。我错误地假设转义码只能有一定数量的选项。事实上,我可以指定任意数量(或实现我的目标所需的数量)。例如:

$e = [char]0x1b
"$e[38;2;255;128;128;48;2;128;0;255;4mtest$e[0m"

... 将生成单词 test,它带有粉红色前景和紫色背景的下划线。分解:

  • 使用Get-PSReadLineOption查看当前设置
  • 某些属性在 256/24 位颜色模式下没有意义。
  • Windows 控制台不支持反向(也在 WSL 中)

Jafrog 博客中的代码已转换为 PowerShell

## Q:\Test19\SO_56679782.ps1

Get-PSReadLineOption

$Esc=[char]0x1b 

'The following command should print “hello” in bright red underscore text:'
"$Esc[91;4mHello$Esc[0m"

ForEach($code in 30..37){
"{0}[{1}mEsc[{1}m{0}[0m  {0}[{1};1mEsc[{1};1m{0}[0m  {0}[{1};3mEsc[{1};3m{0}[0m  {0}[{1};4mEsc[{1};4m{0}[0m  {0}[{2}mEsc[{2}m{0}[0m" -f $Esc,$code,($code+60)
}
pause
foreach($code in 0..255){"{0}[38;5;{1}mESC[38;5;{1}m{0}[0m" -f $Esc,$code}

Ansi Esc[ sequence (CSI)
              Foreground     Background
No Color     normal bright  normal bright
0  black       30     90      40    100
1  red         31     91      41    101
2  green       32     92      42    102
3  yellow      33     93      43    103
4  blue        34     94      44    104
5  violet      35     95      45    105
6  turqoise    36     96      46    106
7  grey        37     97      47    107