PowerTip: Write PowerShell Output in Color Without Using Write-Host

Summary: Write colorized output to the Windows PowerShell console without using the Write-Host cmdlet.

Hey, Scripting Guy! Question How can you write output to the Windows PowerShell console without using the Write-Host cmdlet?

Hey, Scripting Guy! Answer Set ForegroundColor to a different color by using $host.Ui.RawUi, and then use the Write-Output cmdlet to write the output. When you are finished, set the ForegroundColor back to its original color.

PS C:\> $t = $host.ui.RawUI.ForegroundColor

PS C:\> $host.ui.RawUI.ForegroundColor = “DarkGreen”

PS C:\> Write-Output “this is green output”

this is green output

PS C:\> $host.ui.RawUI.ForegroundColor = $t

PS C:\>

Comments (5)

  1. Indranil says:

    In what use cases would we want to do this instead of Write-Host ?


  2. Veleek says:

    When you use Write-Host the content is written directly to the host and not passed on to the rest of the Pipeline. Useful when you want to print out status or informative messages while still passing extra content along in the pipeline, but not helpful
    if you want colored output.

  3. JohnLBevan says:

    This doesn’t quite work as you’d expect:

    PS C:> $t = $host.ui.RawUI.ForegroundColor
    PS C:> $host.ui.RawUI.ForegroundColor = "DarkGreen"
    PS C:> Write-Output "this is green output"
    this is green output
    PS C:> $host.ui.RawUI.ForegroundColor = $t

    [tag:the] output that says "this output is green" is now the original color; since $host.ui.RawUI.ForegroundColor changes the color of everything on screen; not just the lines written whilst the foreground color’s set to green.

  4. Proxx.nl says:

    JohnLBevan… try using console instead of ISE. then it works like expected!

  5. Zee says:

    How do i go back to the original colour?
    now all my host screen font colour is yellow