Powershell Write-host outputting parameters in variable as string

powershell

$mycolorparams = "-foregroundcolor red -backgroundcolor black"

write-host "I want this foreground in Red and background in black" $mycolorparams

Hi All,

This is driving me nuts. When I use write-host the cmdlet returns everything as string:

"I want this foreground in Red and background in black -foregroundcolor red -backgroundcolor black".

Not the actual string with red text and a black background.

The worst part is this was working for me until I changed the var name in my code. I have no idea what has been altered since. I suspect it has something to do with the quotes as single quotes spit out the string and double quotes read the var. But after trying heaps of variations with single and double on both the text and var the results are the same just a string output.

I have been trawling the web for the past hour with no luck, plenty of examples but nothing I can find with the specific problem. Any help appreciated, thanks.

Best Answer

Hmm.. I have a little workaround for you in shape of a wrapper function:

$mycolorparams = " -foregroundcolor red -backgroundcolor black"
function redBlack($text){
    invoke-expression ("write-host " + $text + $mycolorparams)
}

Then execute

redBlack "I want this foreground in Red and background in black"

which will yield a correctly coloured result.

Related Topic