Compile and load the type... this could be pre-compiled e.g. via dotnet CLI then the type loaded via
Assembly.LoadFrom(...) or Add-Type or Import-Module if part of an actual PowerShell Module.
Once loaded you can Update-TypeData -TypeAdapter
like shown in the example:
Add-Type -Path .\adapterExample.cs -WA 0 -IgnoreWarnings
Update-TypeData -TypeAdapter ([MyPropertyAdapter]) -TypeName ([MyCustomClass])If the adapter is part of the a module you can have a ...Types.ps1xml instead and loaded via TypesToProcess:
<?xml version="1.0" encoding="utf-8"?>
<Types>
<Type>
<Name>MyCustomClass</Name>
<TypeAdapter>
<TypeName>MyPropertyAdapter</TypeName>
</TypeAdapter>
</Type>
</Types>Then the actual usage, pretty much like an AD Object... it is actually ADEntityAdapter the one in charge of this...
$class = [MyCustomClass]::new()
$class.Id = [guid]::NewGuid()
$class.Name = 'john.galt'
$class
# Id Name
# -- ----
# bbd94707-59b8-4de8-9624-89bfa2ca6700 john.galt
$class.psobject.Properties
# BaseObject : MyCustomClass
# Tag : bbd94707-59b8-4de8-9624-89bfa2ca6700
# MemberType : Property
# Value : bbd94707-59b8-4de8-9624-89bfa2ca6700
# IsSettable : True
# IsGettable : True
# TypeNameOfValue : Guid
# Name : Id
# IsInstance : True
#
# BaseObject : MyCustomClass
# Tag : john.galt
# MemberType : Property
# Value : john.galt
# IsSettable : True
# IsGettable : True
# TypeNameOfValue : String
# Name : Name
# IsInstance : True
Thanks for putting this together - good to have a simple example of how PowerShell type adapters work.
However, while your sample works for properties, calling methods appears to be broken; e.g. calling
$class.ToString()results in the following error:InvalidOperation: Method invocation failed because [MyCustomClass] does not contain a method named 'ToString'.Curiously - for reasons unknown to me - a method call such as
.ToString()also calls theGetPropertymethod, and unconditionally returning aPSAdaptedPropertyinstance from it seems to be what makes the method call fail.While you could include code in
GetProperty()to detect method names being passed to thepropertyNameparameter, and, if so, returnnullfor them, I wonder if there's a simpler solution.