Home > Net >  How to save color of string into variables
How to save color of string into variables

Time:04-20

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.

CodePudding user response:

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

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

# ... later
Write-Host @hi

CodePudding user response:

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.

  • Related