0
0
PowerShellscripting~5 mins

Object arrays in PowerShell

Choose your learning style9 modes available
Introduction
Object arrays let you store many objects together so you can work with them easily, like a list of friends or tasks.
When you want to keep a list of users with their details.
When you need to store multiple files' information to process later.
When you want to collect results from commands and work with them as a group.
When you want to sort or filter a group of objects based on their properties.
When you want to pass multiple objects to a function or script.
Syntax
PowerShell
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)
)
Use @() to create an array in PowerShell.
Objects can be custom classes or built-in types with properties.
Examples
An empty array with no objects inside.
PowerShell
# Empty object array
$emptyArray = @()
An array with just one object inside.
PowerShell
# Array with one object
$singlePerson = @([PSCustomObject]@{Name='Diana'; Age=28})
An array holding two objects with Name and Age properties.
PowerShell
# Array with multiple objects
$people = @(
    [PSCustomObject]@{Name='Eve'; Age=22},
    [PSCustomObject]@{Name='Frank'; Age=40}
)
Get the first object and print its Name property.
PowerShell
# Access first object in array
$firstPerson = $people[0]
Write-Output $firstPerson.Name
Sample Program
This script creates a Person class, makes an array of Person objects, prints them, adds a new Person, then prints the updated list.
PowerShell
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)"
}
OutputSuccess
Important Notes
Adding an object to an array with += creates a new array behind the scenes, so it is not the fastest for very large arrays.
Access array elements by index starting at 0, like $array[0] for the first object.
Use object arrays when you want to keep related data together and process it easily.
Summary
Object arrays hold many objects together in one variable.
You can create, access, and add objects to these arrays easily.
They help organize data like lists of people or files for scripts.