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?
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.
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.
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.
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   
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With