this post explains how one can consume extension methods in Powershell
http://community.bartdesmet.net/blogs/bart/archive/2007/09/06/extension-methods-in-windows-powershell.aspx
Compare this to what someone does in C# - they add a "using SomeAssembly" and all the extension methods are loaded.
Did this get simpler Powershell 2.0. And if so, what does one do to use extension methods in Powershell 2.0? I have checked the publically available documentation and installed the CTP and am not seeing anything that is helping.
The main advantage of the extension method is to add new methods in the existing class without using inheritance. You can add new methods in the existing class without modifying the source code of the existing class. It can also work with sealed class.
Extension methods are an excellent addition to the C# language. They enable us to write nicer, more readable code. They allow for more functionally styled programming, which is very much needed in an object-oriented language. They also should be used with care.
Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are static methods, but they're called as if they were instance methods on the extended type.
To define and call the extension methodDefine a static class to contain the extension method. The class must be visible to client code. For more information about accessibility rules, see Access Modifiers. Implement the extension method as a static method with at least the same visibility as the containing class.
It doesn't get easier in V2, but there is an extension mechanism which you might not be aware of.
I believe that part of the problem is in PowerShell's handling (or lack thereof) of generics.
Also, for extension methods to be applied, the typed collections would have to be enforced, which is difficult in PowerShell. PowerShell, as a dynamic language, supports building collections of various types and most collections are represented as arrays of Object. Extension methods require the parameters to be inferred from the collection type and then the predicate checked to be of the correct type.
If your concern is for some LINQ like functions, there are a number of cmdlets that provide the same functionality in working with object collections.
PowerShell's extended type system allows you to add methods to various types by adding an xml file or modifying an existing one (creating a new one is the recommended path). Jeffrey Snover demonstrates doing this with adding a ScriptProperty to the Object class in this blog post.
It's not quite the same, but it could get the job done.
If 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