Using the Write-Host Cmdlet
Writing Messages to the Console Window
The Write-Host cmdlet enables you to write messages to the Windows PowerShell console. For example, do you have a pressing need to write the phrase This is a message to the console window? Then just call Write-Host followed by the message you’d like to write:
Write-Host "This is a message"
There’s nothing wrong with that; it writes the phrase This is a message to the console window. However, let’s see if we can get Write-Host to do something even more exciting. As it turns out, Write-Host includes two optional parameters - -foregroundcolor and -backgroundcolor - that enable you to specify a different text color and a different text background color. For example, here’s a command that sets the foreground (text) color to red and the background color to yellow:
Write-Host "This is red text on a yellow background" -foregroundcolor red -backgroundcolor yellow
And here’s what the resulting console window looks like:
We thought you’d like that. Here are the colors you can use with the -foregroundcolor and -backgroundcolor parameters:
Black
DarkBlue
DarkGreen
DarkCyan
DarkRed
DarkMagenta
DarkYellow
Gray
DarkGray
Blue
Green
Cyan
Red
Magenta
Yellow
White
Here’s an interesting variation that displays differently-colored text on the same line as regular text. The command first calls Write-Host and writes the phrase Data for. Notice, however, that it then appends the parameter -nonewline. As the name implies, -nonewline causes the cursor to stay on the current line.
Is that important? You bet it is: by default, any time you call write-Host it tacks a carriage-return linefeed on the end, causing the cursor to drop to the next line in the console window. However, by using -nonewline we leave the cursor in place; that enables us to call Write-Host a second time (separating the individual calls using a semi-colon). This time around we write the name of the computer, but we also do the red-text-on-a-yellow-background thing. We add a semi-colon and then call Write-Host a third time, this time writing the phrase retrieved May 12, 2006 in regular text.
Got all that? Here’s what the command looks like:
Write-Host "Data for " -nonewline; Write-Host "atl-ws-01" -foregroundcolor red -backgroundcolor yellow -nonewline; Write-Host " retrieved May 12, 2006"
And here’s what the resulting console window looks like: