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, 5An 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
$peopleOnce you execute the PowerShell script, you can see the output like the screenshots below:

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
$peopleConclusion
In this PowerShell tutorial, I have explained two methods to Create an Object Array with Properties in PowerShell.
You may also like:
- How to Read Excel Files into an Array in PowerShell?
- How to Check if an Array Contains More than One Value in PowerShell?
- How to Check if an Array Contains a String Case-Insensitive in PowerShell?
Bijay Kumar is an esteemed author and the mind behind PowerShellFAQs.com, where he shares his extensive knowledge and expertise in PowerShell, with a particular focus on SharePoint projects. Recognized for his contributions to the tech community, Bijay has been honored with the prestigious Microsoft MVP award. With over 15 years of experience in the software industry, he has a rich professional background, having worked with industry giants such as HP and TCS. His insights and guidance have made him a respected figure in the world of software development and administration. Read more.