PowerShell: capturing output to log file and console

Recently I had to redirect full PowerShell session to both console and log file. Full means both stdout and stderr needs to be redirected. Working code is worth thousand words:


Stop-Transcript | out-null
$ErrorActionPreference = "Continue"

$OutputFileLocation = "C:\output.log"
Start-Transcript -path $OutputFileLocation -append

Write-Host "This will go into output.log"

# redirecting both STDOUT and STDERR (2>&1) to transcript:
robocopy.exe C:\ D:\ readme.txt 2>&1 | out-host



Line 11 deserves additional explanation. Due to a PowerShell bug 315875 output from native applications will not be captured. That being said, the workaround is to combine stdout and stderr and redirect it to a out-host.

The only remaining limitation is that stderr will be interpreted by PowerShell as error (and rightly so!) and thus printed out in red. While it is a little annoying, your output log doesn’t have colors 🙂


7 thoughts on “PowerShell: capturing output to log file and console

  1. Aziz

    Thanks a bunch, we adopped this code for simlier use for a single commad. Here is what we used. The command that geerated the errors was the get-mailpublicfolder.

    $OutputFileLocation = “\\servername\C$\Aziz\mailpub_error.log”
    Start-Transcript -path $OutputFileLocation -append
    get-mailpublicfolder 2>&1 | out-host


Leave a Reply

Your email address will not be published. Required fields are marked *