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#.

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:

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!