1

By Default, does out-file record stream 1 or stream 6?

If I have a command:

invoke-expression $cmd *>&1 | 
       out-file -encoding ASCII -Append FilePath $log

Which streams does out-file record to a file?

1   Success stream  PowerShell 2.0  Write-Output
2   Error stream    PowerShell 2.0  Write-Error
3   Warning stream  PowerShell 3.0  Write-Warning
4   Verbose stream  PowerShell 3.0  Write-Verbose
5   Debug stream    PowerShell 3.0  Write-Debug
6   Information stream  PowerShell 5.0  Write-Information

Is it just Stream 1? or Stream 6? I get a little bit confused because most shells have only 1 and 2, and powershell adds 6 which is like 1?

mklement0
  • 382,024
  • 64
  • 607
  • 775
pico
  • 1,660
  • 4
  • 22
  • 52
  • 2
    Only stream 1 is piped to `Out-File`, but since you've merged the contents of streams 2 through 6 into stream 1 upstream, the contents from all 6 streams output by `Invoke-Expression` will end up being written to disk – Mathias R. Jessen Nov 04 '21 at 13:37
  • As an aside: [`Invoke-Expression` (`iex`) should generally be avoided](https://stackoverflow.com/a/51252636/45375); definitely [don't use it to invoke an external program or PowerShell script](https://stackoverflow.com/a/57966347/45375). – mklement0 Nov 04 '21 at 15:05

1 Answers1

0

You're using the pipeline (|) to provide input to Out-File.

Only stream 1, the success (data) output stream is sent through the pipeline by default.
The conceptual about_Redirection help topic, from which you quote, documents all 6 PowerShell streams.

Optionally - as you have done - you can merge other streams into stream 1, which causes their output to be included as well.

You can merge:

  • individual streams by their number; e.g. 3>&1 merges the warning stream (3) into the success stream; multiple such redirections may be used.

  • all (other) streams, represented by *, i.e. by using *>&1

Since you are using *>&1, output from all streams is sent through the pipeline and therefore saved to the target file by Out-File.


As an aside: >, the redirection operator (along with >>), is an effective alias of Out-File, so you can use it alone to save to a file - assuming Out-File's default character encoding is acceptable:[1]

& { 'success'; Write-Warning 'warning' } *> allstreams.txt

Targeting files with > also allows you to save individual streams to separate files:

& { 'success'; Write-Warning 'warning' } > data.txt 3> warnings.txt

[1] In PowerShell version 5.1 and above you can change Out-File's default encoding in a manner that also takes effect for >, via the preference variable $PSDefaultParameterValues - see this answer.

mklement0
  • 382,024
  • 64
  • 607
  • 775