How to Create an Array of Objects in PowerShell (With Example)


Often you may want to create an array of custom objects in PowerShell.

You can use the following syntax to do so:

$players = @(
[pscustomobject]@{team="Mavs";points=40;assists=12},
[pscustomobject]@{team="Kings";points=22;assists=7},
[pscustomobject]@{team="Hawks";points=25;assists=11},
[pscustomobject]@{team="Celtics";points=13;assists=9})

This particular example creates an array named $players that contains a total of four custom objects that each contain values for three properties named team, points and assists.

The following example shows how to use this syntax in practice.

Example: How to Create Array of Objects in PowerShell

We can use the following syntax to create an array of custom objects named $players that contains information about four different basketball players:

$players = @(
[pscustomobject]@{team="Mavs";points=40;assists=12},
[pscustomobject]@{team="Kings";points=22;assists=7},
[pscustomobject]@{team="Hawks";points=25;assists=11},
[pscustomobject]@{team="Celtics";points=13;assists=9})

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

Notice that this returns an array of custom objects.

Once we’ve created this array, we can access specific objects by using bracket notation.

For example, we can use the following syntax to access only the second object in the array:

$players[1]

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

PowerShell select specific object in array of objects

We can also use the Select cmdlet to only select specific properties of each object in the array:

$players | Select team, assists

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

PowerShell select specific properties in array of objects

Notice that this returns only the values for the team and assists properties of each object in the array.

Feel free to use the Select cmdlet to select any specific properties of each object that you’d like in your own array.

Related Tutorials

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

PowerShell: How to Compare Two Arrays
PowerShell: How to Create an Array with Initial Size
PowerShell: How to Create an Array of Arrays
PowerShell: How to Remove Duplicate Values from Array

Leave a Reply