Emit custom objects, rather than text, from functions and scripts
Whenever possible, functions (especially) and scripts (to a lesser degree) should emit custom objects, not just text. This ensures that the output of these constructs can be piped to other cmdlets, like Where-Object, Sort-Object, and so forth, further extending PowerShell’s capabilities.
To create a custom object:
$obj = New-Object PSObject
To add properties to the object:
$obj | Add-Member NoteProperty "MyPropertyName" "MyValue"
And repeat as needed to add additional properties. Then output the object to the pipeline:
Write $obj
These output objects can then be sorted, grouped, filtered, and so forth, making your code behave more like a "real" PowerShell cmdlet.
Tags: add-member, custom objects, function output, new-object











March 24th, 2008 at 1:08 pm
Just a suggestion - replace Write with Write-Output so that even the code snippets in the best practices follow the best practices (no aliases).