Write-output is not working with colour

Azure-learning 56 Reputation points
2022-09-29T17:01:08.717+00:00

Hi if I am using below command it's working fine.

Write-Host $variable -ForegroundColor Green.

but I have to use "Writeoutput": It's giving me error. Please let me know how to do this with write-output
Write-output $variable -ForegroundColor Green.

Windows for business Windows Server User experience PowerShell
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. Dillon Silzer 57,826 Reputation points Volunteer Moderator
    2022-09-29T17:06:42.797+00:00

    Hi @NGaur-3476

    This is due to Write-Host and Write-Output being two completely different commands. The Write-Output command does not have the -ForegroundColor flag, so you will not be able to use it for this.

    However, you can install TMOutput as described in https://tommymaynard.com/write-output-gets-foreground-and-background-colors-and-more-2016/

    Install-Module -Name TMOutput

    TMOutput 1.1

    https://www.powershellgallery.com/packages/TMOutput/1.1

    Write-Host

    https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/write-host?view=powershell-7.2

    246145-image.png

    Write-Output

    https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/write-output?view=powershell-7.2

    ------------------------------------

    If this is helpful please accept answer.

    1 person found this answer helpful.
    0 comments No comments

  2. Michael Taylor 60,161 Reputation points
    2022-09-29T17:57:19.653+00:00

    Write-Host and Write-Output are for solving different problems. If you need to display information to the user (such that color matters) then use Write-Host. That is what it is designed for.

    Having said that, if you really, really need to use Write-Output to write colored text on the screen then you can do it but you'll have to rely on the host supporting it and ensure you reset everything back when you're done. You'll want a custom function for this.

       $originalColor = $host.UI.RawUI.ForegroundColor  
       $host.UI.RawUI.ForegroundColor = "Green"  
       Write-Output "Hello"  
       $host.UI.RawUI.ForegroundColor = $originalColor  
    

    You are effectively accessing the underlying host's UI, setting the foreground color, rendering your output and then putting everything back. I don't personally recommend it but that would be a workaround.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.