Powershell – Colorize string output with colorvariables in the output string
The other day I saw a script output that was colored with magenta. I was a bit impressed by the readability of the output messages. As I looked to the source code I saw something (ugly) like:
# Testoutput write-host -nonewline "Creating Link from";write-host -nonewline -f magenta " locationXYZ";write-host -nonewline " to";write-host -nonewline -f magenta " target UVW"
The output looked like:
The Output is not so bad, but the effort is enormous. I came to the idea to encode the colorsettings within the output string. So I ended up with the following Script:
function write-chost($message = ""){
[string]$pipedMessage = @($Input)
if (!$message)
{
if ( $pipedMessage ) {
$message = $pipedMessage
}
}
if ( $message ){
# predefined Color Array
$colors = @("black","blue","cyan","darkblue","darkcyan","darkgray","darkgreen","darkmagenta","darkred","darkyellow","gray","green","magenta","red","white","yellow");
# Get the default Foreground Color
$defaultFGColor = $host.UI.RawUI.ForegroundColor
# Set CurrentColor to default Foreground Color
$CurrentColor = $defaultFGColor
# Split Messages
$message = $message.split("#")
# Iterate through splitted array
foreach( $string in $message ){
# If a string between #-Tags is equal to any predefined color, and is equal to the defaultcolor: set current color
if ( $colors -contains $string.tolower() -and $CurrentColor -eq $defaultFGColor ){
$CurrentColor = $string
}else{
# If string is a output message, than write string with current color (with no line break)
write-host -nonewline -f $CurrentColor $string
# Reset current color
$CurrentColor = $defaultFGColor
}
# Write Empty String at the End
}
# Single write-host for the final line break
write-host
}
}
Now it's possible to use a single string to encode the color by seperating each color with a hashtag (#).
Here is an example:
The syntax is very simple. Choose a color for the next characters and put it into hashtags (#). To stop coloring the characters just put another hashtag behind the colored characters to reset the foreground color to its default.
# Testing write-chost "#green#All these characters are green until you end the coloringprocess with a hashtag.# Now everything is default again"
If you want to use any other charater, or command for the coloring, just replace the hashtag of the split function in line 20 with your character/command. I think this is a usefull function, because script output is often needed and coloring the important parts of the output is sometimes very helpful
Edit: I edited the script to work even if you pipe a string to write-chost like:
PS C:\> "#green# Everything is ok at #magenta#MyServer#" | write-chost

