How to Correctly Wrap Multiple Results

by Sep 5, 2017

Whenever a PowerShell function needs to return more than one kind of information, it is important to wrap them as objects. Only then will the caller be able to discover and uniquely access the information. Here is a quick sample.

This is a function that simply outputs 3 pieces of data. They are returned as an array of different objects:

function test
{
    33.9
    "Hallo"
    Get-Date
}

$result = test

$result.Count
$result

And here is a much better function that returns the same information, but wrapped into a structured object. This way, the user can easily discover the information submitted by the function:

function test
{
    [PSCustomObject]@{
        Number = 33.9
        Text = "Hallo"
        Date = Get-Date
    }

}


$result = test
$result.Count

$result

$result.Number

Twitter This Tip! ReTweet this Tip!