PSCustomObject
PSCustomObject is a minimal object representation over System.Object. Custom properties are allowed as NoteProperty.
In the following example, the PSCustomObject created has the same member as default [object] except the NoteProperty Foo.
[object]::new() | gm
[PSCustomObject]@{ Foo = 'I am a NoteProperty!' } | gm2
Why Do We Need it
Differ from HashTable as a dictionary, [PSCustomObject] is a representation for object literal. The must-know is [PSCustomObject] maps to the same type as [psobject], System.Management.Automation.PSObject. The only valid usage is marking one HashTable as System.Management.Automation.PSCustomObject. Other possible usages of [PSCustomObject] is bascially pointless.
WARNING
Do not use PSCustomObject if case-sensitive keys matter, name of extended properties are not case-sensitive, use HashTable instead.
Creation
PSCustomObject borrows the syntax from HashTable with a casting.
$john = [PSCustomObject] @{
Name = 'John Smith'
Age = 18
}2
3
4
From HashTable
You can explicitly convert a HashTable to PSCustomObject
$table = @{
Foo = 'foo'
}
$obj = [PSCustomObject]$table 2
3
4
5
Or use New-Object, but this might be slower.
$obj = New-Object -TypeName PSObject -Property $tableShallow Copy
$john = [PSCustomObject] @{
Name = 'John Smith'
Age = 18
}
$smith = $john.psobject.Copy()2
3
4
5
6
Add New Members
You can't directly add new properties after declaration using dot accessor. One should use Add-Member to append new members.
$obj | Add-Member -MemberType NoteProperty -Name PropName -Value ValueNOTE
All members of a [pscustomobject] should be extended properties, you can inspect them using $obj.psextended
Enumerating Properties
$obj.psobject.properties | foreach { $_.Value = 0 }