digitalguy99
digitalguy99

Reputation: 549

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.

Upvotes: 1

Views: 1435

Answers (3)

Mathias R. Jessen
Mathias R. Jessen

Reputation: 174785

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

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

# ... later
Write-Host @hi

The @ in front of the variable path/name is known as the splatting operator, you can read more in the about_Splatting help topic

Upvotes: 3

digitalguy99
digitalguy99

Reputation: 549

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

Upvotes: 0

Todd
Todd

Reputation: 5405

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.

Upvotes: 0

Related Questions