Content Redirection

Here’s another item I see in some submisstions of the 2010 Scripting Games that I felt I should address: the use of legacy console redirection. While technically not illegal or wrong, an example like this demonstrates (at least in my opinion) that the scripter hasn’t fully adopted the PowerShell paradigm.

While this will work and create a text file, it is not fully written in the PowerShell spirit. At the very least, you should use the cmdlets Out-File, Add-Content or Set-Content in place of the legacy console redirection operators, > and >>.   I’ll admit that 99 times out of 100 you’ll have no issues with the resulting text file.  However, there is the potential for encoding issues. The cmdlets are better designed to handle encoding as well as a few other PowerShell bells and whistles like –noclobber.

Another reason I suggest using cmdlets is that the > and >> operators are actually part of the underlying command session that PowerShell.exe is running on. It’s conceivable that some future version of PowerShell or some PowerShell hosted application won’t support these operators which means your script will fail and need revision. Stick with cmdlets from the beginning to protect your scripting investment.

Here’s a better PowerShell implementation that uses cmdlets and takes better advantage of the pipeline.

In this example I’m using Tee-Object which not only displays the properties in the console but also redirects to the text file. I’m sure you’ll agree this is better than using > and >>.  Or am I making too much out of this?

One thought on “Content Redirection”

  1. I fully agree. I see > $null a lot when you should use | Out-Null. Powershell is beautiful and expressive and should be used to its fullest. thanks for the port and informing the younger scripters to take the pure path.

Comments are closed.