Creating Your own Types

by Jun 28, 2010

Did you know that you can compile any .NET source code on the fly and use this to create your own types? Here is an example illustrating how to create a new type from c# code that has both static and dynamic methods:

$source = @'
public class Calculator
{
public static int Add(int a, int b)
{
return (a + b);
}

public int Multiply(int a, int b)
{
return (a * b);
}
}
'@
Add-Type -TypeDefinition $source
[Calculator]
[Calculator]::Add(5,10)
$myCalculator = New-Object Calculator
$myCalculator.Multiply(3,12)