Add custom type to a PowerShell Custom Object

Hello,

In a previous post, we saw how to create PowerShell Objects.Today, we’ll see how to add cutom type to those objects. By default, when you create a PowerShell custom object, the object is a “System.Management.Automation.PSCustomObject” :

PowerShell-Object-DefaultType

You can customize this :

$Computer.PSObject.TypeNames.Insert(0,'ItForDummies.Computer')

PowerShell-Object-CustomType

What’s the point ? Let’s look closer. If you look at $Computer :

PowerShell-Object-DefaultDisplay

Now, let’s update type data, and display $Computer again :

Update-TypeData -TypeName 'ItForDummies.Computer' -DefaultDisplayPropertySet Name, OS

PowerShell-Object-DefaultDisplay-Modified

Yes, the default view of the object changed. Don’t worry, other properties are still there :

$Computer | select *

PowerShell-Object-DefaultDisplay-SelectAll

You can also specify the object type when you create it :

[PsCustomObject][Ordered]@{Name = "localhost"; State = "Unknown"; OS = "Unknown"; PsTypeName ='ItForDummies.Computer'}

PowerShell-Object-CustomTypeAtCreation

Leave a Reply