Run a C# .cs file from a PowerShell Script

I saw no reason why we couldn't run a .cs file directly from PowerShell, so I took Keith's snip and added the missing Get-Content parts to do literally what the OP asks for. No need to compile your code, just edit the -Path argument to point to your .cs file.

$source = Get-Content -Path "A:\basic.cs"
Add-Type -TypeDefinition "$source"

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

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

Basic.cs

public class BasicTest
{
    public static int Add(int a, int b)
    {
        return (a + b);
    }

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

You can use Add-Type to compile C# code and add it to the current PowerShell session. Then you call the C# code like you would any other .NET framework code. This is an example from the man page on Add-Type:

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

PS C:\>Add-Type -TypeDefinition $source
PS C:\>[BasicTest]::Add(4, 3)
PS C:\>$basicTestObject = New-Object BasicTest
PS C:\>$basicTestObject.Multiply(5, 2)

You're looking for the wrong thing. Put your C# into an assembly, and call its public classes, functions and methods from PowerShell, just like you would call the .NET Framework from Powershell.

If you really want to compile and run C# source from PowerShell, see Weekend Scripter: Run C# Code from Within PowerShell.

Tags:

C#

Powershell