以编程方式更改 PowerShell 的 16 种默认控制台颜色

Programmatically change PowerShell's 16 default console colours

PowerShell 通过为其 16 种控制台颜色之一(- 由于某种原因被称为 DarkMagenta - )分配一个蓝色值来改进(坦率地说)fugly Windows 控制台配色方案,并将其用作默认屏幕背景。

我想以编程方式将 16 种颜色中的每一种颜色更改为自定义配色方案。例如,在我的 PowerShell 配置文件中。

我找到了关于如何更改将 ConsoleHost 的 16 种颜色中的哪一种分配给不同类型的文本的解释,但我想要的是实际将 ConsoleHost 的 16 种颜色中的每一种更改为不同的十六进制值。 (仅供自己使用,不适用于其他用户或其他控制台,例如cmd.exe。)

当然这可以通过右键单击菜单栏并手动调整 "Properties" 或 "Default" 设置来完成,但这很快就会很累。而且我找不到这些设置的保存位置。

(我已经搜索了注册表和C:\Users\<current_user>\AppData,除了HKCU:\Console下的ColorTable##属性外,一无所获,其范围显然比PowerShell控制台设置更广泛。 )

如果有人能提供帮助,将不胜感激。

我搜索了 "change powershell console color" 并找到了大量示例。

也许这就是您要找的:

How can I set the PowerShell console background color

$Host.UI.RawUI.BackgroundColor = ($bckgrnd = 'DarkBlue')
$Host.UI.RawUI.ForegroundColor = 'White'
$Host.PrivateData.ErrorForegroundColor = 'Red'
$Host.PrivateData.ErrorBackgroundColor = $bckgrnd
$Host.PrivateData.WarningForegroundColor = 'Magenta'
$Host.PrivateData.WarningBackgroundColor = $bckgrnd
$Host.PrivateData.DebugForegroundColor = 'Yellow'
$Host.PrivateData.DebugBackgroundColor = $bckgrnd
$Host.PrivateData.VerboseForegroundColor = 'Green'
$Host.PrivateData.VerboseBackgroundColor = $bckgrnd
$Host.PrivateData.ProgressForegroundColor = 'Cyan'
$Host.PrivateData.ProgressBackgroundColor = $bckgrnd
Clear-Host

关于该主题还有另一个讨论:

Setting Powershell colors with hex values in profile script

控制台颜色在多个地方定义:

  • Global/Default: HKCU:\Console。这适用于所有 conhost.exe 应用程序,包括 cmd.exepowershell.exe.
  • 每个进程: HKCU:\Console\<PROCESS_PATH_WITH_UNDESCORE> 用于特定于进程的更改。前任。 HKEY_CURRENT_USER\Console\%SystemRoot%_System32_WindowsPowerShell_v1.0_powershell.exe 已定义并修改了 ColorTable05ColorTable06.
  • 每个快捷方式: 在快捷方式 (.lnk) 内。这很难以编程方式修改,可能需要 P\Invoke.

您可以使用 PS 使用以下方法修改进程级值:

Set-ItemProperty -Path "HKCU:\Console\%SystemRoot%_System32_WindowsPowerShell_v1.0_powershell.exe" -Name ColorTable04 -Value 5645313

请注意,要查看进程级别的值,您需要使用 运行、windows 资源管理器等启动 PS。如果您使用其中一种快捷方式,则将使用快捷方式的值。因此,修改快捷方式并为新设置保留一份副本可能会更容易。

每个 "ColorTable" 在 System.ConsoleColor-enum 中都有一个硬编码的名称,因此他们只是 "random" 使用了一个名为 DarkMagneta 的名称。可能是因为它是一种独特的颜色,用得不多。

我为 Windows 控制台颜色制作了一个名为 Concfg 的实用程序。

它可以从 JSON 预设文件导入颜色,并负责从注册表和 .lnk 文件中删除覆盖。