SAPIEN Solutions

SAPIEN homepage
PrimalScript script editor+ide
PrimalScope script debugger
Free Tools script utilities
SAPIEN Press tech books
ScriptingAnswers.com learn+share
ScriptingOutpost.com online store
Blog.Sapien.com official blog
Contact Us

 

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.

[Slashdot] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]

Tags: , , ,

One Response to “Emit custom objects, rather than text, from functions and scripts”

  1. Poshoholic Says:

    Just a suggestion - replace Write with Write-Output so that even the code snippets in the best practices follow the best practices (no aliases).

Leave a Reply


Entries (RSS) and Comments (RSS).