How to Run C# Code from PowerShell


Since PowerShell is based on .NET, it can access all .NET libraries. Therefore, it also allow us to execute C# code from PowerShell. In this blog post, we will discuss how to execute C# code from within PowerShell.

Execute C# Code from Within PowerShell

Suppose we have following C# class saved as Calculator.cs.

public class Calculator
    public static int Add(int a, int b)
        return a + b;

    public int Multiply(int a, int b)
        return a * b;

For the sake of brevity, the above class is created to be very simple and to have two kind of methods: static and non-static.

Before instantiating the class, we have to add the class to PowerShell session using Add-Type cmdlet that takes the content of above C# code assuming the powershell script and the c# code are in the same directory.

Next, we can invoke each of the methods depending whether it is a static or non-static method. If it is a static one, we can directly call the method without having to create the object of the class. For non-static method, we must instantiate the class first by using New-Object cmdlet.

$source = Get-Content -Path ".\Calculator.cs"
Add-Type -TypeDefinition "$source"

# Call a static method
[Calculator]::Add(4, 3)

# Create an instance and call an instance method
$calculatorObject = New-Object Calculator
$calculatorObject.Multiply(5, 2)

Following image is the result after we execute above script.

run csharp code from powershell


In order to run C# code from PowerShell, we must add the class to PowerShell using Add-Type. Then, we can instantiate the class using New-Object so that we can call the instance method. If it is a static method, we don’t have to instantiate the class.