Adding Custom Methods to Objects

by Aug 27, 2009

In a previous tip, you learned how to add custom properties to objects. Today, we want to show you how to add custom methods and also give an example how useful this can be.

Let's say you manipulate text and need to find out the word count in a string. You could of course create an external function to do this, but the object oriented approach is to add the necessary commands to the object containing the data. Here is how:

$text = "this is some text"
$text = $text | Add-Member ScriptMethod Words {$this.Split()} -passThru
$text.Words()
@($text.Words()).Count

There are two learning points here: first, a script method actually executes code, and you submit this code as script block in curly braces. Second, the actual object is available inside the script block and represented by $this, so $this.Split() simply calls the built-in string method Split().

Twitter This Tip! ReTweet this Tip!