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.