powershell

How to save color of string into variables


I'm using PowerShell 5.1, and I want to store some colored text into a variable. I'm aware that you can use Write-Host to print out some colored strings into the console, as shown below:

enter image description here

However, I can't seem to save them into a variable:

enter image description here

I've tried various solutions such as the ones given here but nothing seems to work.


Solution

  • Use PowerShell ANSI escape sequences with the format:

    $([char]0x1b)[#m

    where # represents a number. (see here for more info about ANSI escape sequences)

    In the case of the question above, it would look like this:

    enter image description here