1

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.

Ken White
  • 123,280
  • 14
  • 225
  • 444
digitalguy99
  • 443
  • 4
  • 13
  • 1
    if you are using a console/terminal that supports ANSI color codes ... you can save those strings with the color codes. the new-ish windows terminal supports ANSI color codes. – Lee_Dailey Apr 20 '22 at 02:07

3 Answers3

1

You can store the parameter arguments you need for Write-Host in a variable:

$hi = @{ Object = 'hi!'; ForegroundColor = 'Red' }

# ... later
Write-Host @hi
Mathias R. Jessen
  • 157,619
  • 12
  • 148
  • 206
0

The reason the attempt to assign the text output to a variable, $hi = Write-Host ..., is because Write-Host doesn't return the text it prints - it sends the text with ANSI color codes to the console.

You could figure out a convenient scheme for including color information in the text you want to print, and write code that uses that color information as it prints the text to the screen, as suggested by the other posted answer.

For instance,

$text = @'
  { 
    "text": [["The quick ", "red"], ["brown fox ", "blue"], 
             ["jumped over ", "yellow"], ["the lazy ", "cyan"], 
             ["dog", "white"]]
  }
'@
($text | ConvertFrom-Json).text |
         % { Write-Host $_[0] -ForegroundColor $_[1] -NoNewLine }

This could be pretty tedious though. Maybe check PSGallery to see if there are any packages dealing with colorized text that provide commands convenient for your application.

Todd
  • 4,669
  • 1
  • 22
  • 30
0

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

digitalguy99
  • 443
  • 4
  • 13