PowerShell – How to format Write-Host with multiple colors

When you begin to write PowerShell scripts you usually just want it to do some simple tasks and automations. But after a while some scripts grow so large that you actually want to have them output in a bit nicer way.

PSWriteColor Information
Please notice this article contains parts of information (still useful) and may not reflect all functionalities of this module. For download, source code and so on you should refer to the dedicated PSWriteColor module page. After reading this one… of course! It contains useful informationexamples and know-how.
Problem Description

Usually to output information in PowerShell we use Write-Host. By using parameters ForegroundColor and BackgroundColor parameters you can define nice looking output text.

While it's usually good enough for most scripts sometimes formatting one line of script with multiple colors is required. Wouldn't it fun to have Green Red Yellow outputed by PowerShell script?

You can actually do that with 3 „simple lines.

Or even have it as one-liner:

While this works it makes code very hard to read!


But there's actually  a nice and easy way to make it work without much effort. By adding Write-Color function you give yourself couple of options. For example:

Multiple colors in single line, if it's short enough

Or if it's a bit longer…

And the colorful output from this PowerShell method:

This method actually has couple of other features. It allows easy adding of tabbing, lines before and after output. It's useful in creating menu's where it doesn't clutter the output too much. You can for example create:

Options menu

Or adding a tab before your line

Or adding 2 lines, with 2 empty lines before it

And the output of final script:


And log file data properly written to file (it's additive so if you run script multiple times it will not overwrite the log):


You can find the colors you can use by using simple code:

Obviously black is missing :-)

Tags: , , , , , ,

This is a unique website which will require a more modern browser to work! Please upgrade today!