powershellpipepyinstallerstdoutstderr

Tee only STDERR in Powershell without red text


I am using powershell to run a program (pyinstaller) writes all of its progress output to STDERR. I want the output of this command to be both printed on to the console AND saved to a file.

First, I used this: COMMAND | tee compile.log. Everything looked good on the console, but the log file was empty. So, I tried this: COMMAND 2>&1 | tee compile.log. This caused the log file to be written properly, but it caused huge issues:

So, is there something I can use that will both display the progress in the console and write it to a file, but not look like an error?


Solution

  • That is because you only capturing the second (2) Error Stream.

    That stream produces ErrorRecords:

    $Output = Write-Error 'Something went wrong' 2>&1
    $Output.GetType().FullName
    System.Management.Automation.ErrorRecord
    

    That are colored by PowerShell's default display view defined by this property script:

    $FormatData = Get-FormatData System.Management.Automation.ErrorRecord
    $FormatData.FormatViewDefinition.Control.Entries.CustomItems.Expression.Value
    

    (For details see the answer on: How does Powershell know which property to Print out by Default)

    To suppress the red ANSI codes you might simply pipe the output to the Out-String cmdlet as it lets the FormatViewDefinition script belief it writes to something that doesn't support ANSI:

    Write-Error 'Something went wrong' 2>&1 | tee compile.log | Out-String
    

    To capture all (not only the red ErrorRecord) streams, use the asterisk:

    Write-Error 'Something went wrong' *>&1 | tee compile.log | Out-String
    

    The other issue is probably unrelated to the above and indeed too vague for an answer. If that part is still a concern, I would suggest to open a separate question for that, with more details about with Exit Codes you actually get and which exit codes you expect and how you try to capture them.