Objects and Classes
Creating Custom Objects
There are many ways to create a custom object in PowerShell. See this article from TechNet magazine for an overview, as well as the post by The Ginger Ninja. This post by WarrenF describes some interesting ways to decorate those objects.
The most preferable way seems to be using the PSCustomObject
attribute:
$myObject = [PSCustomObject]@{
PropertyA = "a string"
PropertyB = 2
PropertyC = (Get-Date)
}
Measurements suggest that using PSCustomObject
is the fastest approach, see Jonathan Medd's blog post. It is also the cleaner approach.
After creating an object it is possible to give it a typename:
[void]$myObject.PSObject.TypeNames.Insert(0,$TypeName)
# or, equivalently for a collection
$myManyObjects | Add-Member -TypeName $TypeName
This may be useful to associate a custom formatter with the object:
Update-TypeData -DefaultDisplayPropertySet PropertyA,PropertyC -Force -TypeName $TypeName
PowerShell Classes and Object Oriented Programming
Creating classes in PowerShell is very easy. Unlike object which are quite convenient for grouping information together, classes give a cleaner interface for bundling data and functionality.
Some interesting links:
- Michael Willis on Powershell v5 Classes & Concepts