Search code examples
powershellbackground-colorwindows-terminal

Powershell: Get the background color of the Windows Terminal


I use ANSI colors in a Powershell script under Windows 11. In order to adapt the background color of the font to the current background color of the terminal, I would like to read out this Windows terminal background color. However, all methods I know of only return the "default color", which is not correct.

Terminal is set to "Campbell Powershell" color scheme (blue background).

The terminal settings are stored in a JSON file under "%LOCALAPPDATA%\Packages\Microsoft.WindowsTerminal_8wekyb3d8bbwe\LocalState\settings.json". I could extract the settings there. But it would be easier if someone knew a simpler way to get the terminal background color in Powershell.

I tried:

PS C:\> $Host.ui.RawUI.BackgroundColor
Black

PS C:\> [console]::BackgroundColor
Black

Both commands return Black, which is the scheme but not the color!


Solution

  • I hate to give a negative answer here, but sometimes one is warranted when the data supports it.

    Short answer: This is not yet available in Windows Terminal. There is a feature request (#3178) for it that has been (according to the Windows Terminal team) fairly low on the backlog for a while now.


    Longer explanation:

    When your script uses ANSI escape codes to set the colors, those take effect on Windows Terminal. However, the $Host.ui settings are for PowerShell itself and are separate from the Windows Terminal values.

    As a result, what we need is a way to programmatically read the current Windows Terminal ANSI color code settings. Unfortunately, that's not yet available.

    This answer mentions the method for doing so in xterm, and those codes are implemented in quite a few terminal emulators, but (from the parent issue of that comment) not yet in Windows Terminal (issue #3718).

    I doubt that reading the JSON settings is going to help in this case, since that's not going to represent the current state of the terminal based on the ANSI escape codes you've set.

    I'd love to offer you some other workaround, but I wasn't able to come up with one in a few tries.