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?
+8
A:
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.
- "-in": This is short for inputObject and essentially says add member to this
- "-memberType": There are many different types of values you can add to a runtime object including methods, note properties, code method, etc ... See "get-help add-member -full" for a complete list
- "-passthru": Take the object that just had a member added to it and push it down the pipeline. Without this flag the assignment would be assigning and empty pipeline to
$a
. - The assignment call is basically ensuring that
$a
now has the method you added
JaredPar
2009-05-08 17:38:34
+1 Could you elaborate on the syntax a little. The $a = add-member looks a little strange and what does the -in and -passthru switches do?
tyndall
2009-05-08 17:45:08
@Tyndall, updated with comments
JaredPar
2009-05-08 17:48:47
Thanks JaredPar
tyndall
2009-05-08 17:57:05
Add-Member also works with the pipeline PS> $a = "foo"PS> $a | add-member -memberType ScriptMethod -name Bar -value { $this + "bar" } PS> $a.Foo()foobar
Steven Murawski
2009-05-10 18:21:07
@JaredPar: A few questions: "$a = Add-Member" seems to make "$a = $null". Shouldn't the member type be "ScriptProperty" and the call "$a.Bar()"? I must be mising something, but I only got this working by changing all that (PS V1).
guillermooo
2009-05-11 20:10:20
Well, Tyndall wanted a method, not a property.
JasonMArcher
2009-05-11 22:02:48
Very true. I was missing the "-passthru" switch... However, I still don't get what's the point of calling Foo() when then new method was named Bar()... :-?
guillermooo
2009-05-11 22:44:28
+8
A:
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)
Steven Murawski
2009-05-10 18:28:18
I did stumble upon this method. Not sure. I'd like to keep as much as I can in PowerShell versus XML. hmmm. I guess I would use this method if I had lots and lots of "mods" to do.
tyndall
2009-05-11 22:45:35