In a previous tip, we explained how you can add a custom data type to your own custom objects that you might want to return from a function, and then use PowerShell 3.0's new Update-TypeData to define the standard object properties.
This approach works well, but it defines a permanent new type. Here's an example that defines a custom standard object properties "on the fly" without touching the PowerShell type database:
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 [String[]]$properties = 'Name','ID','Language' # the next line is one long line: [System.Management.Automation.PSMemberInfo[]]$PSStandardMembers = New-Object System.Management.Automation.PSPropertySet DefaultDisplayPropertySet,$properties # the next line is one long line: $resultset | Add-Member -MemberType MemberSet -Name PSStandardMembers -Value $PSStandardMembers $resultset }
It works beautifully: in PowerShell 3.0, the function now returns objects that by default only display the properties you want, and in PowerShell 2.0, the solution falls back to standard behavior:
PS> Get-SomeResult Name ID Language ---- -- -------- Weltner 123 PowerShell PS> Get-SomeResult | Select-Object * Name : Weltner FirstName : Tobias ID : 123 Language : PowerShell Skill : 5