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.

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!

Advertisements