views:

447

answers:

2

Hi, I'm currently putting together some Powershell cmdlets. Building them is easy enough but I don't know if I'm building them in an acceptable manner (so to speak).

Are there any guidelines/best practices that one should follow for passing data into the Powershell pipeline? At the moment I'm actually output a single object of type DataSet - if any cmdlet wanted to use it downstream then they would have to loop over the DataTables in that DataSet, then loop over the DataRows in each DataTable.

I guess the question is....am I going to p!ss anyone off by doing this? Or should I be outputting data that is inherently a bunch of rows?

Thanks all in advance

-JT

+5  A: 

It's acceptable to output whatever type of object is best used to represent what you're writing out - a DataSet is absolutely fine. The only potential caution is that v2 of PowerShell may find itself running on a reduced version of the .NET Framework (such as on Server Core), so if that's a potential scenario for your cmdlets, you need to use some caution to make sure the object you're outputting exists on every system where your cmdlet might be used.

All that said, the pipeline works best when it contains collections of objects; a DataSet isn't a collection per se. In other words, you want downstream cmdlets to be able to receive one object at a time via the pipeline, so that those cmdlets don't have to manually enumerate through an object. I don't know a lot about exactly what you're doing - it could well be that a DataSet is entirely appropriate - but I'd generally prefer to see a cmdlet loop through the DataSet internally, create its own custom objects (so that each column in the table becomes a property), and output those objects to the pipeline. That simply increases the number of downstream cmdlets that can consume what you're putting out.

A simple test is to pipe your cmdlet's output to Export-CSV. If it works (and it probably wouldn't with a DataSet), then you're doing the right thing generally. Now, you may well need to create a cmdlet which outputs a DataSet and you only intend for certain other cmdlets you've written (which consume DataSets) to operate against that output. Nothing wrong with that. Max flexibility is single objects, though, since it enables all of PowerShell's core cmdlets to work on your output.

Hope that helps.

Don Jones
+1  A: 

MSDN has an amazing set of Cmdlet Development Guidelines which I found extremely useful when developing my own. They are broken up into three different sections:

Scott Saad