0
0
PowerShellscripting~5 mins

Custom objects (PSCustomObject) in PowerShell

Choose your learning style9 modes available
Introduction

Custom objects let you group related information together in one place. They make data easier to organize and use.

When you want to store multiple pieces of related data like a person's name and age.
When you need to create a simple record or table of information.
When you want to pass structured data between commands or scripts.
When you want to display data in a clear, readable format.
When you want to add custom properties to data for automation tasks.
Syntax
PowerShell
@{ Property1 = 'Value1'; Property2 = 'Value2' } | ForEach-Object { [PSCustomObject]$_ }
Use @{ } to create a hashtable of properties and values.
Pipe the hashtable to ForEach-Object with [PSCustomObject] to create the custom object.
Examples
This creates a custom object with Name and Age properties and shows it.
PowerShell
$person = @{ Name = 'Alice'; Age = 30 } | ForEach-Object { [PSCustomObject]$_ }
$person
This is a shorter way to create a custom object directly from a hashtable.
PowerShell
$car = [PSCustomObject]@{ Make = 'Toyota'; Model = 'Corolla'; Year = 2020 }
$car
Access a property of the custom object using dot notation.
PowerShell
$book = [PSCustomObject]@{ Title = 'PowerShell Guide'; Pages = 250 }
$book.Title
Sample Program

This script creates a custom object for a student with three properties. Then it prints each property clearly.

PowerShell
$student = [PSCustomObject]@{
    Name = 'John Doe'
    Grade = 'A'
    Age = 16
}

Write-Output "Student Info:"
Write-Output "Name: $($student.Name)"
Write-Output "Grade: $($student.Grade)"
Write-Output "Age: $($student.Age)"
OutputSuccess
Important Notes

You can add as many properties as you want to a PSCustomObject.

Custom objects are great for organizing data in scripts and making output easier to read.

Use dot notation to get or set property values.

Summary

Custom objects group related data with named properties.

Use @{ } with [PSCustomObject] to create them easily.

They help organize and display data clearly in PowerShell scripts.