How to Create an Object Array with Properties in PowerShell?

In this PowerShell tutorial, I will explain how to create an object array with properties in PowerShell.

To create an object array with properties in PowerShell, you can use the PSCustomObject type and a loop or a predefined list to populate the array. For example: $objectArray = @(); $objectArray += [PSCustomObject]@{Property1 = ‘Value1’; Property2 = ‘Value2’}. This will create an array of custom objects with specified properties.

Arrays and Objects in PowerShell

Before we dive into creating object arrays with properties, let’s first understand what arrays and objects are in PowerShell.

An array is a data structure that can hold multiple values. In PowerShell, you can create an array by simply separating values with commas. For example:

$numbers = 1, 2, 3, 4, 5

An object in PowerShell is an instance of a class that can contain data in the form of properties and methods. You can create a custom object using the New-Object cmdlet or by casting a hashtable to the [pscustomobject] type. For example:

$person = New-Object -TypeName PSObject -Property @{
    Name = 'John Doe'
    Age = 30
}

or

$person = [pscustomobject]@{
    Name = 'John Doe'
    Age = 30
}

Create an Object Array with Properties in PowerShell

Now, let’s combine these concepts to create an array of objects, each with its own set of properties in PowerShell.

Method 1: Using Custom Objects

You can create an array of custom objects by defining each object and then adding it to an array. Here’s how:

# Create an empty array
$people = @()

# Define custom objects and add them to the array
$people += [pscustomobject]@{
    Name = 'John Doe'
    Age = 30
}
$people += [pscustomobject]@{
    Name = 'Jane Smith'
    Age = 25
}

# Display the array
$people

Once you execute the PowerShell script, you can see the output like the screenshots below:

Create an Object Array with Properties in PowerShell

Method 2: Inline Array Initialization

This is another method to Create an Object Array with Properties in PowerShell.

$people = @(
    [pscustomobject]@{
        Name = 'John Doe'
        Age = 30
    },
    [pscustomobject]@{
        Name = 'Jane Smith'
        Age = 25
    }
)

# Display the array
$people

Conclusion

In this PowerShell tutorial, I have explained two methods to Create an Object Array with Properties in PowerShell.

You may also like: