Add Objects to an Array of Objects in PowerShell

Rohan Timalsina Mar 12, 2022
Add Objects to an Array of Objects in PowerShell

Arrays are a data structure that stores a collection of multiple items. Most programming languages have arrays as the fundamental feature.

Arrays can contain one or more items in PowerShell. The items can be the same or different types.

They can be a string, an integer, an object, or even another array. A single array can have any combination of these items.

Each item is stored in the index number, which starts at zero. The first item is stored at 0, second at 1, third at 2, etc.

An array of objects is the collection of objects. This tutorial will teach you to add objects to an array of objects in PowerShell.

Here is an example of creating an array $data containing objects in Name and Age.

$data = @(
    [pscustomobject]@{Name='Rohan';Age='21'}
    [pscustomobject]@{Name='John';Age='30'}
)

Use += to Add Objects to an Array of Objects in PowerShell

The Plus Equals += is used to add items to an array. Every time you use it, it duplicates and creates a new array.

You can use the += to add objects to an array of objects in PowerShell.

The following example adds an array of objects $data.

$data += [pscustomobject]@{Name='Sam';Age='26'}

Now, check the elements of $data.

$data

Output:

Name  Age
----  ---
Rohan 21
John  30
Sam   26

You can access the objects from an array by enclosing the index number in brackets.

For example:

$data[2]

Output:

Name Age
---- ---
Sam  26

As shown below, the individual objects can be accessed by specifying the property.

$data[2].Name

Output:

Sam
Rohan Timalsina avatar Rohan Timalsina avatar

Rohan is a learner, problem solver, and web developer. He loves to write and share his understanding.

LinkedIn Website

Related Article - PowerShell Array