Add Properties to Objects in PowerShell

  1. Use Hashtable to Create Custom Objects in PowerShell
  2. Use Add-Member to Add Properties to Objects in PowerShell
Add Properties to Objects in PowerShell

This article will discuss how we can add properties to PowerShell objects.

Use Hashtable to Create Custom Objects in PowerShell

Before adding properties to an object, we must create one first. And one way to do this is through hashtables.

To briefly define, hashtables are sets of keys or value pairs that we need to create and assign an object’s properties in PowerShell. In the example, we are creating a hashtable that represents a single object and its properties.

Once the hashtable, $sampleHashtable, has been defined, we can then use the PSCustomObject type accelerator to create an instance of the PSCustomObject class.

And after running the code snippet, we will obtain an object $sampleHashtable of type PSCustomObject with properties defined in the program.

Example 1:

## Define the hashtable
$sampleHashtable = @{
    ID = 1; 
    Shape = "Square"; 
    Color = "Blue"
}
## Create an object
$ShapeObject = [PsCustomObject]$sampleHashtable

Alternatively, we can use the New-Object cmdlet to create our objects using hashtables.

We will be using the same hashtable. However, instead of using the PSCustomObject type accelerator, we will do it with the long-form way with New-Object.

Example 2:

## Define the hashtable
$sampleHashtable = @{
    ID = 1; 
    Shape = "Square"; 
    Color = "Blue"
}
## Create an object
$ShapeObject = New-Object -TypeName PsObject -Properties $sampleHashtable

As we can see, after creating $sampleHashtable, we will be able to reference each property as if it came from a built-in PowerShell cmdlet such as Get-Service.

Use Add-Member to Add Properties to Objects in PowerShell

Not only can we create custom objects in PowerShell, but we can also add to them through the help of the Add-Member command.

The Add-Member cmdlet does not list members but adds them instead. Now, using the same object we created above, we can add custom properties by piping Add-Member to it.

Example:

$ShapeObject | Add-Member -MemberType NoteProperty -Name 'Sides' -Value '4'

Write-Output $ShapeObject

Output:

Color  Shape   ID  Sides
----- .------  --  -----
Blue   Square  1    4
Marion Paul Kenneth Mendoza avatar Marion Paul Kenneth Mendoza avatar

Marion specializes in anything Microsoft-related and always tries to work and apply code in an IT infrastructure.

LinkedIn

Related Article - PowerShell Object