I want to output many different foreground colors with one statement.
PS C:\\> Write-Host \"Red\" -ForegroundColor Red
Red
This output i
Here is small a function I wrote to output colored text (it is actually smaller, but I rewrote it to be more understandable):
function Write-Color() {
Param (
[string] $text = $(Write-Error "You must specify some text"),
[switch] $NoNewLine = $false
)
$startColor = $host.UI.RawUI.ForegroundColor;
$text.Split( [char]"{", [char]"}" ) | ForEach-Object { $i = 0; } {
if ($i % 2 -eq 0) {
Write-Host $_ -NoNewline;
} else {
if ($_ -in [enum]::GetNames("ConsoleColor")) {
$host.UI.RawUI.ForegroundColor = ($_ -as [System.ConsoleColor]);
}
}
$i++;
}
if (!$NoNewLine) {
Write-Host;
}
$host.UI.RawUI.ForegroundColor = $startColor;
}
It's quite simple to use: just use Write-Color "your text"
and add some color name between curly brackets where you want the text to be colored.
Examples:
`Write-Color "Hello, {red}my dear {green}friend !"` will output
Script screenshot
You can put it in your $profile
file to use it in a simple PowerShell prompt, or just add it to some scripts.