Monday, February 18, 2008 4:12 PM
Stream-Oriented Programming in PowerShell
While preparing my PowerShell presentation a few weeks ago, I was reminded of this explanation of stream processing from the SICP lectures.
This concept is widely used in Unix shells, but is really taken to the next level in PowerShell. In fact, after using it for a while, Unix style text stream processing seems primitive in comparison.
In PowerShell, commands emit streams of objects. When you use a pipe to connect commands, each object on the output of the first command is sent to the next one -- not a string representation, but the object itself. Since PowerShell is essentially a .NET reflection-based object automator -- most of this happens in-process (no serializing).
And, writing commands in .NET is simple -- I used O'Reilly's PowerShell Cookbook, by Lee Holmes (highly recommended) to learn how -- but essentially, a cmdlet is a simple class that implements System.Management.Automation.Cmdlet. Your public properties are automatically turned into command-line arguments (with one, optionally coming from the pipe), and then all you need to do is implement ProcessRecord(), which will be called for each input object. PowerShell manages the pipeline -- you just need to worry about one object at a time.
It's a powerful concept, but to fully take advantage of it, you'll need to wrap your OO designed objects in Cmdlets.