Calling Extension Methods in PowerShell

A quick one because it’s Friday night.

I recently found myself translating some C# code into PowerShell.  If you’ve done this, you know that most of it is really routine.  Change the order of some things, change the operators, drop the semicolons.

In a few places you have to do some adjusting, like changing using scopes into try/finally with .Dispose() in the finally.

But all of that is pretty straightforward.

Then I ran into a method that wasn’t showing up in the tab-completion.  I hit the dot, and it wasn’t in the list.

I had found….and extension method!

Extension Methods

In C# (and other managed languages, I guess), an extension method is a static method of a class whose first parameter is declared with the keyword this.

For instance,


public static class MyExtClass {
    public static int NumberOfEs (thisstring TheString)
    {
        return TheString.Length-TheString.Replace ("e", "").Length;
    }
}

Calling this method in C# goes like this: “hello”.NumberOfEs().

It looks like this method (which is in the class MyExtClass is actually a string method with no parameters.

Extension Methods in PowerShell

Unfortunately, PowerShell doesn’t do that magic for you. In PowerShell, you call it just like it’s written, a static method of a different class.

So, in PowerShell, we would do the following:

$code=@'
public static class MyExtClass {
    public static int NumberOfEs (this string TheString)
    {
        return TheString.Length - TheString.Replace ("e", "").Length;
    }
}
'@
add-type -TypeDefinition $code 

[MyExtClass]::NumberOfEs('hello')

Note that I’ve included the C# code in a here-string and used add-type to compile it on the fly.

The point is, when translating extension method calls into PowerShell, you need to find the extension class (in this case MyExtClass) and call the static method directly.

You learn something every day.

–Mike

3 Comments

  1. Pingback: Dew Drop - October 9, 2017 (#2577) - Morning Dew

Comments are closed.