I want to output many different foreground colors with one statement.
PS C:\> Write-Host "Red" -ForegroundColor Red
Red
This output is red.
PS C:\> Write-Host "Blue" -ForegroundColor Blue
Blue
This output is blue.
PS C:\> Write-Host "Red", "Blue" -ForegroundColor Red, Blue
Red Blue
This output is magenta, but I want the color to be red for the word red, and blue for the word blue via the one command. How can I do that?
I found a much easier option at https://blogs.technet.microsoft.com/heyscriptingguy/2011/05/17/writing-output-with-powershell/
Basically, the first write-host includes the option -NoNewLine. This prevents the new line from forming. The next write-host will be added immediately after the previous text. And each of the separate write-host can have -foregroundcolor options. That can be repeated for each color change you need.
Example with one line of text with three colors:
Notice that there is a space after the text in the first and second write-host. PowerShell is not concatenating or combining the text, it is simply not moving the cursor to the next line.
This code is available with a different number of arguments: Text, ForeGroundColor, and BackGroundColor.
Each colorlist is used with a rotate implementation:
Log usage:
List Usage (just 2 backGroundColor and 4 foreGroundColor):
Standard Write-Host
Slight modification to this one... I took version 2, removed the logging (because I don't want it), and then added a Boolean parameter, similar to -NoNewLine for Write-Host. I was specifically trying to add the ability to change the colors and prompt for user input on the same line so that I could highlight the default answer if the user does not enter anything.
I realize this was available in Write-HostColored (in a previous answer)... but sometimes you just want simpler code...
Sample of what I was trying to accomplish:
Find advanced function
Write-HostColored
below, which allows embedding coloring instructions in a string, both for the foreground and the background color:The above yields:
In addition to accepting a default foreground and background color with
-ForegroundColor
and-BackgroundColor
, you can embed one or more color specifications in the string to write, using the following syntax:<fgcolor>
and<bgcolor>
must be valid[ConsoleColor]
values, such asgreen
orwhite
(case does not matter). Everything following the color specification up to the next#
, or implicitly up to the end of the string, is written in that color.Write-HostColored
source code (PSv2+):This works too...
You could roll your own Write-Color command or something that looks for inline tokens that change the color. This is how ANSI escape sequences used to work back in the BBS days.
But you could achieve what you want by doing:
Here's a simple little function that does what you asked.