PowerShell PSCustomObject
Cmdlets return objects with properties, and your scripts should too. The easiest way to make your own object is [pscustomobject]: write a hashtable literal and cast it. The result behaves exactly like the objects cmdlets return: it sorts, filters, formats as a table and exports to CSV or JSON.
Creating objects
$server = [pscustomobject]@{
Name = 'web01'
Role = 'frontend'
Cores = 4
Online = $true
}
$server
$server.Name
$server.GetType().Name
Name Role Cores Online
---- ---- ----- ------
web01 frontend 4 True
web01
PSCustomObject
Unlike a plain hashtable, the properties keep the order you wrote them, and they are shown as a table with column headers.
Hashtable or object?
@{ } hashtable |
[pscustomobject]@{ } |
|
|---|---|---|
| Purpose | lookup by key | a record with properties |
| Pipeline | one object (the whole table) | one object per record |
| Display | Name/Value columns |
one column per property |
| Export-Csv / ConvertTo-Json | awkward | natural |
| Add a field | $h.new = 1 |
Add-Member or Select-Object |
$asHash = [ordered]@{ Name = 'web01'; Cores = 4 } # [ordered] keeps the display stable
$asObject = [pscustomobject]@{ Name = 'web01'; Cores = 4 }
$asHash
$asObject
Name Value
---- -----
Name web01
Cores 4
Name : web01
Cores : 4
A plain @{ } hashtable makes no promise about key order (it can even differ between runs), which is why this example uses [ordered]. A [pscustomobject] always keeps the order you wrote.
Collections of objects
The real power appears when you have many records. Build an array of objects and every pipeline cmdlet works on it:
$servers = @(
[pscustomobject]@{ Name = 'web01'; Role = 'frontend'; Cores = 4 }
[pscustomobject]@{ Name = 'db01'; Role = 'database'; Cores = 16 }
[pscustomobject]@{ Name = 'web02'; Role = 'frontend'; Cores = 2 }
)
$servers | Sort-Object Cores -Descending | Format-Table
$servers | Where-Object Role -eq 'frontend' | ForEach-Object Name
($servers | Measure-Object Cores -Sum).Sum
Name Role Cores
---- ---- -----
db01 database 16
web01 frontend 4
web02 frontend 2
web01
web02
22
Adding and changing properties
Assigning to an existing property just works. To add a new property, use Add-Member or Select-Object with a calculated property:
$book = [pscustomobject]@{ Title = 'Dune'; Pages = 412 }
$book.Pages = 896 # change an existing property
$book | Add-Member -NotePropertyName Author -NotePropertyValue 'Frank Herbert'
$book
$withLength = $book | Select-Object *, @{ Name = 'Long'; Expression = { $_.Pages -gt 500 } }
$withLength.Long
Title Pages Author
----- ----- ------
Dune 896 Frank Herbert
True
Objects from functions
A function that outputs objects instead of formatted text is reusable: the caller decides how to filter, sort, display or export the result.
function Get-Rectangle {
param([double]$Width, [double]$Height)
[pscustomobject]@{
Width = $Width
Height = $Height
Area = $Width * $Height
Perimeter = 2 * ($Width + $Height)
}
}
$shapes = @(
Get-Rectangle -Width 2 -Height 3
Get-Rectangle -Width 5 -Height 5
Get-Rectangle -Width 1 -Height 10
)
$shapes | Sort-Object Area | Select-Object Width, Height, Area | Format-Table
$shapes | ConvertTo-Json -Compress
Width Height Area
----- ------ ----
2.00 3.00 6.00
1.00 10.00 10.00
5.00 5.00 25.00
[{"Width":2.0,"Height":3.0,"Area":6.0,"Perimeter":10.0},{"Width":5.0,"Height":5.0,"Area":25.0,"Perimeter":20.0},{"Width":1.0,"Height":10.0,"Area":10.0,"Perimeter":22.0}]
Inspecting properties
Every object has a hidden PSObject member that describes it. It's useful to loop over properties generically, for example to print any object as key: value lines:
$user = [pscustomobject]@{ Login = 'ada'; Team = 'research'; Admin = $false }
foreach ($prop in $user.PSObject.Properties) {
'{0,-6}: {1}' -f $prop.Name, $prop.Value
}
$user.PSObject.Properties.Name -join ', 'Login : ada
Team : research
Admin : False
Login, Team, Admin
Tip: Give a custom object a type name for nicer formatting or for your own checks:
$obj.PSObject.TypeNames.Insert(0, 'Contoso.Server').
Test yourself
How do you create a custom object with properties Name and Age?
- New-Object @{Name='x';Age=1}
- [pscustomobject]@{ Name = 'x'; Age = 1 }
- @{ Name = 'x'; Age = 1 }.ToObject()
- [object]('x', 1)
Why should functions output objects instead of formatted strings?
- Objects print faster
- The caller can still sort, filter, format and export them
- Strings can't be returned
- Objects use less memory
Which command adds a NEW property to an existing PSCustomObject?
- $o.New = 1 always works
- Add-Member -NotePropertyName New -NotePropertyValue 1
- Set-Property
- New-Item