Using the Add-Type PowerShell cmdlet to create new C# classes on the fly

Posted: (EET/GMT+2)

 

PowerShell's Add-Type cmdlet lets you drop a bit of C# code right inside your script when you need something extra, like a little helper C# method or class that isn't built in.

Here's a small example that adds a simple C# class and uses it immediately:

Add-Type -TypeDefinition @"
using System;
public class MathTools
{
    public static int Square(int x) { return x * x; }
}
"@

[MathTools]::Square(7)

You can also use it to add .NET references:

Add-Type -AssemblyName System.Windows.Forms
[System.Windows.Forms.MessageBox]::Show("Hello from PowerShell and C#")

This is great when you want to experiment or build small utilities without compiling anything separately. For more complex types, you can also pass a -Path that points to a .cs file or -ReferencedAssemblies if your code needs extra DLLs.

Happy scripting!