Occasionally, PowerShell code is supposed to output warnings and reports, so colors can add more readability to it. Traditionally, PowerShell supported color only through its Write-Host cmdlet:

PS> Write-Host 'WARNING!' -ForegroundColor Red -BackgroundColor White

That turned out to be impractical for many purposes, though, because if you wanted to mix colors in one line, you’d have to split the line into multiple calls to Write-Host and use -NoNewLine as a workaround:

Write-Host 'Here is a ' -NoNewline
Write-Host 'WARNING' -ForegroundColor Red -BackgroundColor White -NoNewline
Write-Host '. Please respond.'

Produces this output:

Here is a WARNING. Please respond.  

PowerShell 7 directly supports ANSI escape sequences, too, that can set color and additional things in a string-based way. Try this in a PowerShell 7 console:

PS> "Here is a `e[0m`e[7;39;41mWARNING!`e[0m. Please respond." 
Here is a WARNING. Please respond.  

In an old Windows PowerShell console (and inside the PowerShell ISE), you instead get the raw string output.

There are plenty of resources on the web that explain the ANSI string format (i.e. https://duffney.io/usingansiescapesequencespowershell/). In a nutshell, in the example above the ANSI sequence starts with the escape character (`e[…m) where “…” represents additional code for what formatting you want. “`e[0m”, for example, resets formats to default. “`e[7;3X;4Ym sets background and foreground colors where X and Y is a number between 0 and 9.

Twitter This Tip! ReTweet this Tip!