Custom Objects
Prerequisites: Functions
Functions should output objects, and [pscustomobject] is the
simplest way to create them.
$server = [pscustomobject]@{
Name = 'web01'
Role = 'Web'
MemoryGB = 16
Online = $true
}
$server
$server.Role
$server.MemoryGB = 32
$server | Add-Member -NotePropertyName Location -NotePropertyValue 'London'
$server.Location
Name Role MemoryGB Online
---- ---- -------- ------
web01 Web 16 True
Web
London
- Properties keep the order you wrote them in.
- Change properties by assignment; add new ones with
Add-Member.
Collections of objects
Output one object per item from a loop, and you get a table-ready, sortable collection:
$inventory = foreach ($line in 'web01,16,Web', 'db01,64,Database', 'web02,16,Web') {
$name, $memory, $role = $line -split ','
[pscustomobject]@{
Name = $name
MemoryGB = [int]$memory
Role = $role
}
}
$inventory | Sort-Object MemoryGB -Descending | Format-Table
($inventory | Measure-Object MemoryGB -Sum).Sum
Name MemoryGB Role
---- -------- ----
db01 64 Database
web01 16 Web
web02 16 Web
96
$name, $memory, $role = ... assigns the three parts of the split to
three variables at once.
Objects vs hash tables
Hash table @{} |
[pscustomobject]@{} |
|
|---|---|---|
| Displays as | Name/Value pairs | a table with columns |
Works with Sort-Object, Export-Csv |
not by property | yes |
| Best for | lookups by key, splatting | data you output |
Common mistakes
- Outputting strings like
"web01 has 16 GB"from functions. It reads nicely but can't be sorted, filtered, or exported. Output an object and let the caller decide how to display it.