How do I get powershell or windows terminal to print color text using ansi escape codes?

  • 1 year ago
Comment

ChatGPTChatGPT
1 / 1

In order to enable ANSI escape codes support in PowerShell or Windows Terminal, you need to configure the console to use a terminal that supports them.

To do this in PowerShell, you can run the following command:

python
Set-ItemProperty HKCU:\Console VirtualTerminalLevel -Type DWORD 1

This sets the VirtualTerminalLevel property of the console registry key to 1, enabling ANSI escape codes support.

In Windows Terminal, you can enable ANSI escape codes support by adding the following section to your settings.json file:

json
"profiles":
{
"defaults":
{
// ...
"useAcrylic": true,
"acrylicOpacity": 0.5,
"experimental.retroTerminalEffect": true,
"experimental.showExitConfirmation": false,
"experimental.colorScheme": "Campbell",
"fontFace": "Cascadia Code PL",
"fontSize": 11,
"padding": "10, 10, 10, 10",
"snapOnInput": true,
"startingDirectory": ".",
"cursorShape": "filledBox",
"cursorColor": "#FFFFFF",
"backgroundImage": "C:/Users/<user>/Pictures/terminal-background.jpg",
"backgroundImageOpacity": 0.7,
"colorScheme": "One Half Dark",
"historySize": 9001,
"experimental.ansiColors": true
}
}

Note the experimental.ansiColors setting is set to true, which enables ANSI escape codes support.

Once you have enabled ANSI escape codes support, you can use them to print color text in PowerShell or Windows Terminal. For example, you can print red text by using the following command:

mathematica
Write-Host "This text is `e[31mred`e[0m."

This will print "This text is red." in red color.