Reputation: 409
$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.
Upvotes: 1
Views: 17888
Reputation: 95652
Use argument splatting (though I think it wasn't in old versions so you might need to upgrade to Powershell version 3 or later).
PS C:\> $opts = @{ForegroundColor="red"; BackgroundColor="black"; object="Hello world"}
PS C:\> write-host @opts
Hello world
or:
PS C:\> $opts = @{ForegroundColor="red"; BackgroundColor="black"}
PS C:\> write-host @opts -object "Hello world"
Hello world
You'll need to convert your options string into either a hashtable or an array. In fact if you run help about_Splatting
you'll find one of the examples exactly covers your question:
This example shows how to re-use splatted values in different commands. The commands in this example use the Write-Host cmdlet to write messages to the host program console. It uses splatting to specify the foreground and background colors.
To change the colors of all commands, just change the value of the $Colors variable. The first command creates a hash table of parameter names and values and stores the hash table in the $Colors variable. $Colors = @{ForegroundColor = "black" BackgroundColor = "white"} The second and third commands use the $Colors variable for splatting in a Write-Host command. To use the $Colors variable, replace the dollar sign ($Colors) with an At symbol (@Colors). # Write a message with the colors in $Colors Write-Host "This is a test." @Colors # Write second message with same colors. # The position of splatted hash table does not matter. Write-Host @Colors "This is another test."
Upvotes: 5
Reputation: 10107
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.
Upvotes: 4