Controlling Object Property Display

by Nov 27, 2012

When you create functions that return custom objects, there is no way for you to declare which functions should display by default. PowerShell always displays all properties, and when there are more than 4, you get a list display, else a table:

function Get-SomeResult
{
    $resultset = New-Object PSObject | 
      Select-Object Name, FirstName, ID, Language, Skill
    $resultset.Name = 'Weltner'
    $resultset.FirstName = 'Tobias'
    $resultset.ID = 123
    $resultset.Language = 'PowerShell'
    $resultset.Skill = '5'


    $resultset
} 

The result is a list display:

PS> Get-SomeResult


Name      : Weltner
FirstName : Tobias
ID        : 123
Language  : PowerShell
Skill     : 5 

In PowerShell 3.0, you can now define the parameters of a type that should be displayed by default. To make that work with your function, first assign a new custom type to your return objects, and then call Update-TypeData to tell PowerShell which properties it should display for this type of data:

function Get-SomeResult
{
    $resultset = New-Object PSObject | 
      Select-Object Name, FirstName, ID, Language, Skill
    $resultset.Name = 'Weltner'
    $resultset.FirstName = 'Tobias'
    $resultset.ID = 123
    $resultset.Language = 'PowerShell'
    $resultset.Skill = '5'
    
    # this section defines the default properties
    # and assigns the returned custom objects the
    # "type" name: myObject. Choose a different one
    # for each type of return object your functions use

    if ($Host.Version.Major -ge 3)
    {
        $objectType = 'myObject'
        $resultset.PSTypeNames.Add($objectType)
        if ((Get-TypeData $objectType) -eq $null)
        { 
          $p = 'Name','ID','Language'
          Update-TypeData -TypeName $objectType -DefaultDisplayPropertySet $p 
        }
    }

    $resultset
} 

It works beautifully in PowerShell 3.0 and falls back to default behavior in PowerShell 2.0:

PS> Get-SomeResult

Name                                                     ID Language
----                                                     -- --------
Weltner                                                 123 PowerShell

PS> Get-SomeResult | Select-Object *
Name      : Weltner
FirstName : Tobias
ID        : 123
Language  : PowerShell
Skill     : 5

ReTweet this Tip!