6

#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 {
    param([object]$o)
    if($o -is [int]) { $this | foreach {$_ * $o} }
}

@(1..5).map(2)

2
4
6
8
10

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: , , ,

6 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 {

    param([scriptBlock]$Script)

    $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’.

Leave a Reply

Submit Comment

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