2

How to redirect stdout and stderr to file and console separately in PowerShell?

Go through all the sites, I find basically there are two method, but NEITHER can fully satisfy the requirement

  1. & .\test.ps1 2>&1 | tee .\out.txt

In this case , stdout and stderr can still be shown on console, but they will be combined in the same file

  1. & .\test.ps1 2>error.txt | tee out.txt

This is the workaround I saw from SilverNak. However as he said, stderr will not be shown on console

cherishty
  • 373
  • 2
  • 5
  • 13

1 Answers1

1

To show both success output and error stream output in the console and capture it in stream-specific files, extra work is needed:

# Create / truncate the output files
$null > out.txt
$null > error.txt

# Call the script and merge its output and error streams.
& .\test.ps1 2>&1 | ForEach-Object {
  # Pass the input object through (to the console). 
  $_
  # Also send the input object to the stream-specific output file.
  if ($_ -is [System.Management.Automation.ErrorRecord]) { $_ >> error.txt }
  else                                                   { $_ >> out.txt }
}
mklement0
  • 382,024
  • 64
  • 607
  • 775