Returning Rich Objects from Functions (Part 1)

If a PowerShell function needs to return more than one information kind, always make sure you wrap the pieces of information inside a rich object. The easiest way to produce such a custom object is [PSCustomObject]@{} like this:

function Get-TestData 
{
  # if a function is to return more than one information kind,
  # wrap it in a custom object

  [PSCustomObject]@{
      # wrap anything you'd like to return
      ID = 1
      Random = Get-Random
      Date = Get-Date
      Text = 'Hallo'
      BIOS = Get-WmiObject -Class Win32_BIOS
      User = $env:username
    }
}

The core of the custom object is a hash table: any hash table key turns into a property. The awesome thing about this approach is that you can use variables and even commands inside the hash table, so it is easy to collect all the information you want to return, and combine it in one self-descriptive object:

 
PS> Get-TestData


ID     : 1
Random : 1794057589
Date   : 25.05.2018 13:06:57
Text   : Hallo
BIOS   : \DESKTOP-7AAMJLFrootcimv2:Win32_BIOS.Name="1.6.1",SoftwareElementID="1.6.1",SoftwareElementState=3,TargetOperatingSys
         tem=0,Version="DELL   - 1072009"
User   : tobwe
 

Twitter This Tip! ReTweet this Tip!

GD Star Rating
loading...