PowerShell, Extension Methods, and Monkey Patching

泪湿孤枕 提交于 2019-12-06 22:20:12

问题


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?


回答1:


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



回答2:


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)



来源:https://stackoverflow.com/questions/840907/powershell-extension-methods-and-monkey-patching

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!