powershellansi-escapetext-coloringwrite-host

Is there any way to send the nice colouring that write-output achieves through write-host/information etc?


in my function inside a catch block I want to send the get-error details out to the host, and if we are in a terminal, it is nicer to have the different colours that the default formatting produces. However when you push that default formatting through Out-String | Write-Host, we lose the nice colouring.

Is there any way to keep the nice colouring.. especially for get-error as it puts red underlines at the important pieces in very large stacks?

before somone suggests it, I do not want to send the exception to the success stream

function blah {
try {
  throw 'blah'
} catch {
  $_ | Get-Error | Out-String | Write-Host
  $_ | Get-Error # this produce nice coloured text, but it goes to the success stream, which I don't want
  }
}

Solution

  • You can do the following:

    function blah {
      try {
        throw 'blah'
      }
      catch {
        $oldVal = $PSStyle.OutputRendering
        $PSStyle.OutputRendering = 
          [Console]::IsOutputRedirected ? 'PlainText' : 'ANSI'
        $_ | Get-Error | Out-Host
        $PSStyle.OutputRendering = $oldVal
      }
    }
    

    Note: