509.949.2162 jeremy@bondbyte.com

Ever wanted to run a snippet of C# code in PowerShell? Some times this is useful for testing code in environments without requiring a full deployment of software. This can also be used and an advanced troubleshooting technique.

Open a PowerShell Prompt with Elevated permissions.

Load your C# class into a string variable

C:\Temp>$source = @"
public class MathClass
{
    public static int Add(int a, int b)
    {
        return (a + b);
    }

    public int Multiply(int a, int b)
    {
        return (a * b);
    }
}
"@

* notice the @” and the “@ these need to be on their own line.

Load string containing C# code into PowerShell

C:\Temp> Add-Type -TypeDefinition $source

Call a Method in the Class

C:\Temp> [MathClass]::Add(4, 3)