PowerShell 2.0: One Cmdlet at a Time #107 Add-Type

Continuing the series looking at new cmdlets available in PowerShell 2.0. This time we look at the Add-Type cmdlet.

What can I do with it?

Imbed code from modern programming languages into your PowerShell session or scripts. The list of valid languages are: C#, C# 3.0, VisualBasic and JScript – C# is the default. Use the Language parameter to specify one if it is not C#.

Add-Type1

Example:

Within a PowerShell session use some C# code to create a TakeAway class and create a static method Minus. Use the Add-Type cmdlet to add the class to the session and then call the TakeAway class and Minus static method.

$csharp = @"
public class TakeAway
{
    public static int Minus(int a, int b)
    {
        return (a - b);
    }
}
"@
Add-Type -TypeDefinition $csharp
[TakeAway]::Minus(10,7)

You will see that we get the expected answer of 3:

Add-Type2

How could I have done this in PowerShell 1.0?

PowerShell 1.0 did not support adding C# or other code into PowerShell scripts, you could however have created your own cmdlet which I’m sure would have been very straightforward for most sysadmins :-)

1000 things 1% better!

3 thoughts on “PowerShell 2.0: One Cmdlet at a Time #107 Add-Type

  1. Thanks Luc!

    You are correct about the lack of Remove-Type, I believe this is a limitation from .NET. once it’s been loaded into a session, it cannot be unloaded, or even updated.

    Thanks
    Jonathan

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>