Right usage of 2>&1 | tee or | tee with powershell

Viewed 8451

I want to see the output of the command in the console and save it in a file so I have these two options:

When I use command | tee output.txt somehow it generates no output file at all but it works as usual in the console.

When I use command 2>&1 | tee output.txt it generates a fine output file but the text in the console appears in red. enter image description here

Is there any way to either fix the first option or let the text appear as usual in the second one? I am using Windows PowerShell (Windows 10) and the Programm I am using this for is liquibase 3.5.5. just for the case that this is important.

2 Answers

In PowerShell, redirecting stderr lines from an external program to PowerShell's success stream via 2>&1 wraps those lines in [System.Management.Automation.ErrorRecord] instances in case they are captured for further processing.

In Windows PowerShell, these captured instances render like PowerShell errors, which is why you're seeing the red output (by contrast, without the redirection, the stderr lines would be passed through to the console, without coloring).

A simple workaround is to convert these objects to strings explicitly, which outputs the original lines (PSv3+ syntax; built-in alias % for ForEach-Object used for brevity):

... 2>&1 | % ToString | Tee-Object output.txt

Note: This workaround is no longer necessary in the install-on-demand, cross-platform PowerShell (Core) 7+ edition, where even captured stderr lines now consistently render just as strings.

If you are in DOS then you can leverage powershell (from DOS) and use tee-object do more or less a tee like in Linux.

C:\> powershell some_command ^| tee-object -FilePath some_outputfile

The ^ escapes the pipe so that the pipe applies to powershell and not DOS.

Powershell and tee-object should come with Windows as standard so nothing to install!

Related