PowerShell: How to Use Add-Member with Multiple Values


You can use the Add-Member cmdlet in PowerShell to add members (properties and methods) to a PowerShell object.

Often you may want to use the Add-Member cmdlet to add multiple members to an object at once.

One way to do so is by simply using the Add-Member cmdlet multiple times:

$obj | Add-Member -Name 'Rebounds' -Type NoteProperty -Value 8
$obj | Add-Member -Name 'Blocks' -Type NoteProperty -Value 4

If you would prefer a one-liner approach, you can use calculated properties instead:

$obj = $obj | Select-Object *, @{n='Rebounds';e={8}}, @{n='Blocks';e={4}}

The following examples show how to use each of these methods in practice with the following object in PowerShell named $team_data:

$my_data = [ordered]@{
  'Team' = 'Mavs'
  'Points' = 25
  'Assists' = 7
}

$team_data = New-Object -Type PSObject -Property $my_data

The following example shows how to use each of these methods in practice.

Example 1: Add Members to Object by Using Add-Member Multiple Times

One way to add several members to an object at once is by using the Add-Members cmdlet multiple times.

For example, we can use the following syntax to add members named ‘Rebounds’ and ‘Blocks’ to the object named $team_data:

$team_data | Add-Member -Name 'Rebounds' -Type NoteProperty -Value 8
$team_data | Add-Member -Name 'Blocks' -Type NoteProperty -Value 4

The following screenshot shows how to use this syntax in practice:

PowerShell Add-Member multiple values

Notice that when we use the Get-Member cmdlet to display the properties of this object, we can see that ‘Rebounds’ and ‘Blocks’ were both successfully added as properties to the object.

Example 2: Add Members to Object by Using Calculated Properties

Another way to add several members to an object at once is to use calculated properties with the following syntax:

$team_data = $team_data | Select-Object *, @{n='Rebounds';e={8}}, @{n='Blocks';e={4}}

The following screenshot shows how to use this syntax in practice:

PowerShell Add-Member with multiple values using calculated properties

When we use the Get-Member cmdlet to display the properties of this object, we can see that ‘Rebounds’ and ‘Blocks’ were both added as properties to the object.

Note #1: The terms n and e in the calculated properties are aliases for name and expression, respectively.

Note #2: You can find the complete documentation for the Add-Member cmdlet in PowerShell here.

Related Tutorials

The following tutorials explain how to perform other common tasks in PowerShell:

PowerShell: How to List All Object Properties
PowerShell: How to Use Group-Object with Multiple Properties
PowerShell: How to Use Sort-Object with Multiple Properties

Leave a Reply