Introduction
Object arrays let you store many objects together so you can work with them easily, like a list of friends or tasks.
class Person {
[string]$Name
[int]$Age
Person([string]$name, [int]$age) {
$this.Name = $name
$this.Age = $age
}
}
# Create an array of Person objects
$people = @(
[Person]::new('Alice', 30),
[Person]::new('Bob', 25),
[Person]::new('Charlie', 35)
)# Empty object array
$emptyArray = @()# Array with one object $singlePerson = @([PSCustomObject]@{Name='Diana'; Age=28})
# Array with multiple objects $people = @( [PSCustomObject]@{Name='Eve'; Age=22}, [PSCustomObject]@{Name='Frank'; Age=40} )
# Access first object in array $firstPerson = $people[0] Write-Output $firstPerson.Name
class Person {
[string]$Name
[int]$Age
Person([string]$name, [int]$age) {
$this.Name = $name
$this.Age = $age
}
}
# Create an array of Person objects
$people = @(
[Person]::new('Alice', 30),
[Person]::new('Bob', 25),
[Person]::new('Charlie', 35)
)
Write-Output "People before adding new person:"
foreach ($person in $people) {
Write-Output "$($person.Name), Age $($person.Age)"
}
# Add a new person to the array
$newPerson = [Person]::new('Diana', 28)
$people += $newPerson
Write-Output "`nPeople after adding new person:"
foreach ($person in $people) {
Write-Output "$($person.Name), Age $($person.Age)"
}$array = @() $array += 'apple' $array += 'banana' $array += 'cherry' $array
$array = @() $array += 'one' $array = $array + 'two' $array = $array + 3 $array
$people = @(
[pscustomobject]@{Name='Alice'; Age=30},
[pscustomobject]@{Name='Bob'; Age=25},
[pscustomobject]@{Name='Carol'; Age=35}
)Pass the test and this pattern moves unknown