#PSTip Extending Type Data

Note: This tip requires PowerShell 3.0 or above.

In the previous article Matt used lambda functions to simplify data manipulation . In this tip I want to show you a way of using functions as methods by extending the System.Array class.

Beginning in Windows PowerShell 3.0 we can use the Update-TypeData to update types with new type data. In previous versions of PowerShell this operation required writing a ps1xml file (lots of XML to deal with). Here’s an example that adds a ‘map’ script method to Array objects :

Update-TypeData -Force -MemberType ScriptMethod -MemberName map -TypeName System.Array -Value {
    if($o -is [int]) { $this | foreach {$_ * $o} }



One caveat of the new added method is its signature. When viewed using the Get-Member cmdlet we can see that the method doesn’t accept any arguments though the script block used to extend the type is using a param block with one parameter ($object).

PS> Get-Member -InputObject @(1..5) -MemberType ScriptMethod

   TypeName: System.Object[]

Name MemberType   Definition
---- ----------   ----------
map  ScriptMethod System.Object map();

In the same manner , we can use Update-TypeData to “attach” new functionality to .NET types. Check the help of Update-TypeData for more information and code examples.

Filed in: Columns, Tips and Tricks Tags: , , ,

8 Responses to "#PSTip Extending Type Data"

  1. Bartek Bielawski says:

    Shouldn’t it be:

    Update-TypeData -Force -MemberType ScriptMethod -MemberName map -TypeName System.Array -Value {


    $this | foreach $Script


    (1..10).map({$_ * 2})


    • ShayLevy says:

      It could be. With your example a scriptblock containing arbitrary code can be passed in, and it can execute virtually anything, not necessarily what ‘map’ should do. It could encapsulate any of the mentioned functions and in this case should have a more generic name, such as ‘Invoke’.

      Anyway, I was showing a simple way to create the function as a method and put the logic in the method. I think I should also call the method ‘multiply’ and not ‘map’.

  2. It is truly a great and useful piece of info. I’m satisfied that you simply shared this helpful information with us.
    Please stay us informed like this. Thanks for sharing.

Leave a Reply

Submit Comment

© 2018 PowerShell Magazine. All rights reserved. XHTML / CSS Valid.
Proudly designed by Theme Junkie.
%d bloggers like this: