Advanced Windows PowerShell Scripting Video Training

Advanced Windows PowerShell Scripting Video Training
Advanced Windows PowerShell Scripting Video Training

Monday, October 29, 2012

How to write a string of text in multiple colors in PowerShell

One of the features about PowerShell that drew my attention away from VBScript many years ago was PowerShell’s ability to output information in multiple colors.  When you use Write-Host to display text on the screen, you also get to use the ForegroundColor and BackgroundColor parameters to change the font colors for that line of text.

What if you wanted to have a line of text with different colors?  To do this you will need to to use several Write-Host lines.  The problem with that is that you will have your text on multiple lines.  In the Help file for Write-Host, I noticed a parameter NoNewLine that will not put a return at the end of the text.  Your next Write-Host statement will appear on the same line.  Take a look at the code below and the output.

Write-host "This is some" -ForegroundColor Green -NoNewline
Write-Host "string" -ForegroundColor Red -BackgroundColor DarkRed -NoNewline
Write-Host "in different" -ForegroundColor Gray -BackgroundColor DarkYellow -NoNewline
Write-Host "Colors"

image

2 comments:

Robert Alex. Golden said...

Thanks for posting this. -nonewline is what I needed!

Erik Curtis said...

Thanks...