Avoid Using Redirection

by Aug 10, 2015

While you can still use the old redirection operator to write command output to a file, you should rather use PowerShell cmdlets instead. Here is why:

#requires -Version 2

$OutPath = "$env:temp\report.txt"

Get-EventLog -LogName System -EntryType Error, Warning -Newest 10 > $OutPath

notepad.exe $OutPath 

This produces a text file that exactly represents what else would have been displayed in the console, not taking into consideration the flexible object nature.

The next example makes sure no part of the output text is truncated, and the output uses UTF8 encoding–all options that you don’t have with simple redirection:

#requires -Version 2

$OutPath = "$env:temp\report.txt"

Get-EventLog -LogName System -EntryType Error, Warning -Newest 10 |
Format-Table -AutoSize -Wrap |
Out-File -FilePath $OutPath -Width 100

notepad.exe $OutPath

Twitter This Tip! ReTweet this Tip!