Adding Custom Methods to Types

by Aug 28, 2009

In a previous tip, we have added a new script method to a string called Words() which would split the string into words. But is it worth the effort? After all, your new Words() method would only be available in that single instance of a string. You would have to manually add the method to every string where you wanted to use it.

As it turns out, you can teach PowerShell to add members to object types by default. This is done by the Extended Type System (ETS). To add the Words() method to every single string, launch Notepad and enter this:

<?xml version="1.0" encoding="utf-8" ?>
<Types>
<Type>
<Name>System.String</Name>
<Members>
<ScriptMethod>
<Name>Words</Name>
<Script>
$this.Split()
</Script>
</ScriptMethod>
</Members>
</Type>
</Types>

Save it as "myExtension.ps1xml", and then load it into the PowerShell ETS:

Update-TypeData myExtension.ps1xml

Immediately, every new string created automatically has a new method called Words():

$text = "This is a text"
$text.Words()
@($text.Words()).Count

The two places to look at in your XML template are the type name (here: System.String) that you want to append and inside the Tag ScriptMethod, the name and script code of your new method.
Updates to the ETS are temporary and only apply to the current session. You may want to add your call to Update-TypeDate to one of your profile scripts so the extension is loaded automatically when you launch PowerShell.

Twitter This Tip! ReTweet this Tip!