Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to specify a font color when using write-output

Tags:

I have a powershell script that gives some status output via write-output. I am intentionally not using write-host because the output may be captured and written to a logfile like this:

./myscript.ps1 | out-file log.txt 

But if the output is not redirected it would be nice to have colored output on the console, because the script is producing a lot of different status messages. I know that colored output is possible with write-host but the status messages should be pipeable.

Any ideas how to solve this?

like image 614
binford Avatar asked Jan 10 '11 14:01

binford


People also ask

What are the differences between write-Host & write output in PowerShell?

In a nutshell, Write-Host writes to the console itself. Think of it as a MsgBox in VBScript. Write-Output , on the other hand, writes to the pipeline, so the next command can accept it as its input. You are not required to use Write-Output in order to write objects, as Write-Output is implicitly called for you.

What is write output in PowerShell?

Write-Output sends objects to the primary pipeline, also known as the "output stream" or the "success pipeline." To send error objects to the error pipeline, use Write-Error . This cmdlet is typically used in scripts to display strings and other objects on the console.


2 Answers

I have tried this extra function and it basically works fine:

function Write-ColorOutput($ForegroundColor) {     # save the current color     $fc = $host.UI.RawUI.ForegroundColor      # set the new color     $host.UI.RawUI.ForegroundColor = $ForegroundColor      # output     if ($args) {         Write-Output $args     }     else {         $input | Write-Output     }      # restore the original color     $host.UI.RawUI.ForegroundColor = $fc }  # test Write-ColorOutput red (ls) Write-ColorOutput green (ls) ls | Write-ColorOutput yellow 

The result of this particular test is a little bit funny though: we really get lines in red, green and yellow but the table header is in red, i.e. the color of the the first call of the function.

like image 142
Roman Kuzmin Avatar answered Oct 10 '22 01:10

Roman Kuzmin


This way:

function Green {     process { Write-Host $_ -ForegroundColor Green } }  function Red {     process { Write-Host $_ -ForegroundColor Red } }  Write-Output "this is a test" | Green Write-Output "this is a test" | Red 

enter image description here

like image 34
Francesco Mantovani Avatar answered Oct 10 '22 02:10

Francesco Mantovani