Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PowerShell, Extension Methods, and Monkey Patching

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?

like image 529
BuddyJoe Avatar asked May 08 '09 17:05

BuddyJoe


2 Answers

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)

like image 197
Steven Murawski Avatar answered Oct 28 '22 21:10

Steven Murawski


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
like image 36
JaredPar Avatar answered Oct 28 '22 21:10

JaredPar