Is it possible to write extension method in PowerShell? or to bolt a new method on top of an existing type like [string] live at runtime?
If you have a method or property you want to add to a particular type, you can create a custom type extension via PowerShell's adaptive type system.
A custom type extension is a an XML file that describes the property or script method to a type and then load it into the PowerShell session via the Update-TypeData cmdlet.
A great example of this can be found on the PowerShell Team Blog - Hate Add-Member? (PowerShell's Adaptive Type System to the Rescue)
I don't know of a way to patch a type with an extension method. But it's certainly possible to patch an object via the add-member cmdlet
PS> $a = "foo"
PS> $a = add-member -in $a -memberType ScriptMethod -name Bar -value { $this + "bar" } -passthru
PS> $a.Foo()
foobar
EDIT Explain the completely and totally readable PowerShell Syntax :)
I love PowerShell but it really does come up with cryptic syntax from time to time.
$a
.$a
now has the method you addedIf you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With