Using C# code in PowerShell Scripts

Hi guys, very short post today! Since PowerShell has access to .NET framework assemblies, you can use C# code either from source *.cs files or embed it directly in your script like I’ve done here.


$Source = @"
namespace CSharpPSTest
{
public static class PSTest
{
private static string _result = "Default Value";
public static string Get()
{
return "Get Success: " + _result;
}
public static string Set(string s)
{
_result = s;
return "Set Success: " + _result;
}
}
}
"@
Add-Type TypeDefinition $Source Language CSharp

Then you can call on your C# methods using the following from the prompt:

PS > .\csharp_in_powershell.ps1
PS > [CSharpPSTest.PSTest]::Get()
Get Success: Default Value
PS > [CSharpPSTest.PSTest]::Set("New Value")
Set Success: New Value

If you’re using a lot of functions in your script then writing them in C# can be a good way to simplify the logic as right now there’s much better tool support available for C# than PowerShell. You can do a lot more with your C# code than what I’ve shown here but hopefully it’ll be a good starting point for you!