PowerShell 3 Goes With The Flow
- By Jeffery Hicks
One of the challenges many people face with PowerShell is the difficulty in capturing output from other pipelines like errors and verbose. Success output you could always pipe to Out-File, but that was it. PowerShell v3.0 adds new console redirection operators that allow you to redirect or even merge these other streams into one or more text files. These streams are numbered, as shown in this table:
To redirect you can use the legacy console redirection characters. Use '>' to direct to a text file, '>>' to append to a file and '>&' to merge streams together. Here's a simple example:
PS C:\> get-wmiobject win32_computersystem -comp $env:computername,FOO 2>wmierr.txt
Success results are written to the pipeline normally but all errors are redirected to C:\wmierr.txt If you wanted to also save results to a file this is possible:
PS C:\> get-wmiobject win32_computersystem -comp $env:computername,FOO 1>result.txt 2>wmierr.txt
But I think I would prefer to continue to use Out-File:
PS C:\> get-wmiobject win32_computersystem -comp $env:computername,FOO 2>wmierr.txt | Out-file Results.txt
When using the console redirection characters you can't control things like encoding or take advantage of the other features in Out-File. The other thing that remains to be seen is how these will play out in other PowerShell implementations. Remember, PowerShell is an engine that can be hosted by an application and I don't think there's a guarantee that every feature, like this, will be available in every implementation. But, PowerShell v3 is still very new as I write this so time will tell.
That said, I like the ability to merge outputs:
PS C:\ get-process foo,powershell 2>&1 | out-file proc.txt
This will take the error stream and merge it with the success stream which can then be piped to Out-file which will contain errors and results. Right now you can only merge with the success stream, 1. But you can merge many:
PS C:\> c:\scripts\myscript.ps1 4>&1 3>&1 2>&1 1>>results.txt
This command will merge Verbose, Errors and Warnings with the success pipeline and append the results to a file, results.txt. If you have a lot of v2 scripts that take advantage of Write-Verbose and Write-Warning, stream redirection will be a big help.
If you have access to PowerShell v3.0 be sure to take a look at the help file about_redirection.
Jeffery Hicks is an IT veteran with over 25 years of experience, much of it spent as an IT infrastructure consultant specializing in Microsoft server technologies with an emphasis in automation and efficiency. He is a multi-year recipient of the Microsoft MVP Award in Windows PowerShell. He works today as an independent author, trainer and consultant. Jeff has written for numerous online sites and print publications, is a contributing editor at Petri.com, and a frequent speaker at technology conferences and user groups.