PowerShell is built on top of the CLR (Common Language Runtime) of .NET, which means the two are already deeply connected. But here’s something that often surprises people: you can actually use .NET directly inside PowerShell.

If you’ve read my last two blogs, you know I’ve been diving into event-driven architecture,  specifically how it can be consumed from .NET into PowerShell. In this post, I’m taking things one step further.

I’ll walk you through how to consume C# code inside your PowerShell scripts. Why bother? Because sometimes you’ll hit a scenario so specific, so niche, that native PowerShell just doesn’t cut it the way you need. In those rare moments, you can drop in a bit of C# to supercharge your script and get the exact behavior you want.

Throughout this post, you’ll see the 🎬 icon, which means it’s time to take action so you can get the full benefit from what you’re reading.

You’ll also see 📒, which marks sections that dig deeper into the technical details, giving you the “how” and the “why” behind the code.

Let’s get started.

Todays toolbelt

The “superpower” of PowerShell is that it’s built right on top of the .NET framework. And C#? Well, that’s basically NET’s native tongue.

Translation: they’re best buddies. 🤝

This means we can sneak some C# right into our PowerShell scripts and suddenly do things that PowerShell alone might shrug at.

Two ways we’ll be rolling with it today:

Inline/Outline C# snippets – Drop C# code directly into your script using Add-Type. Think of it like duct-taping a laser pointer to your Swiss Army knife.

Pre-built assemblies – Got a .dll from a C# project? We can load it into PowerShell and start calling its methods like they’ve been there all along.

🤔 “But how does it actually work?”

When you run Add-Type with C# code, PowerShell says “no problem” and compiles it for you on the fly, instantly making your shiny new C# classes and methods available in your session. It’s like hiring a specialist on the spot who already knows the job.

By the end of this, you’ll have scripts that combine PowerShell’s easy-going vibe with C#’s precision, basically the scripting equivalent of having coffee ☕ and cake 🍰 at the same time.

To Inline… or Not to Inline? 🤔

In our first example, we’re bringing in an external C# file, yes! the classic .cs extension. Why? Because when you keep it in a separate file, you get to enjoy the sweet, sweet perks of IntelliSense. Auto-complete, syntax highlighting, all the little hints that save you from pulling your hair out. 💆‍♂️

📒 Sure, you could go inline, where your C# code is basically just a giant string sitting inside your PowerShell script. But then you lose IntelliSense, and you’re basically typing blindfolded while walking a tightrope, a lot more room for typos, and way more sensitive to errors.

🎬 Lets get started!

  • Make sure you have one directory and place the .ps1 and cs file in there. In my example I’m using the files as shown below

  • Lets now give the .cs file some csharp code to get tested
  • For now we can use the example code as shown below
using System; 
	
public class CSharpCode
{
    public static void Main(string[] args)
    {
        Console.WriteLine("Hello, PowerShell from c#!");
    }
}
  • And give the PowerShell file the code shown below
$cSharpCode = Get-Content -Path "CSharpCode.cs" -Raw
Add-Type -TypeDefinition $cSharpCode -Language CSharp

[CSharpCode]::Main(@())
  • Now run the PowerShell code and you will see the result below:

🎇 Just like that! We now have already a running example on how to consume the C# code into PowerShell.

💡 Add-Type adds the file, when you make changes to the C# code and try to run again you might be running into issues that the type already exists. Close your PowerShell session and start again this will clear the loaded types (or use code to clean up the loaded types 😉)

Passing parameters

You can even pass parameters from our PowerShell code to the C# code. It’s very straight forward and in this paragraph I’ll show you how to do it.

🎬 First let’s modify the C# code!

  • Modify your C# code so it looks as shown below
using System; 

public class CSharpCode
{
    public static void Main(string[] args)
    {
        Console.WriteLine("Hello, PowerShell from c#!");
        Console.WriteLine("I received the following arguments:");
        foreach (var arg in args)
        {
            Console.WriteLine(arg);
        }
    }
}
  • Now modify the PowerShell code something like this:
$cSharpCode = Get-Content -Path "CSharpCode.cs" -Raw
Add-Type -TypeDefinition $cSharpCode -Language CSharp

[CSharpCode]::Main(@("Parameter 1", "Parameter 2"))
  • Run your PowerShell script (remember, you might need to restart your IDE if you already ran your script before). You should see the result below;

📒 Keep in mind that the PowerShell version on your system probably is using C# version 6. Which doesn’t support things like string interpolation yet. Some things might be limited in the C# version you are using.

Compiling a DLL and consuming it

Your .cs file can also be compiled as DLL so you can distribute it and utilize it through PowerShell as well.

📒 Before you can continue you need to have a CS compiler (which normally is shipped with Visual Studio). If you don’t have it make sure you get it on your system before continuing.

🎬 Follow the steps below to compile your CS code

  • Run the command below in the root of where your .cs file is located
 . "C:\Program Files\Microsoft Visual Studio\2022\Professional\MSBuild\Current\Bin\Roslyn\csc.exe" -target:library -out:CSharpCode.dll CSharpCode.cs

💡 Your path might be different, make sure your path above points to the correct csc file

  • You should get the result below

And the created DLL in your directory

  • Now let’s consume that DLL. Make a new file like ‘ExampleDLL.ps1” and give it the code below
Add-Type -Path ".\CSharpCode.dll"
[CSharpCode]::Main(@("Param1","Param2"))
  • Now run the code and you should see the output below

🎇 See? Exactly the same, only now we are using the DLL instead of the CS code which gets interpretated during runtime!

Summary

Wrapping It Up, PowerShell Meets C# 🎉

So, what did we unlock today? The powerful secret handshake between PowerShell and C#: two best buddies working side by side to supercharge your scripts. 💥

We started by seeing how easy it is to drop external C# files into PowerShell, giving you IntelliSense love and a cleaner workflow. Then we played with inline snippets, quick and handy but a bit more error-prone (hello, tightrope walk!).

You learned how Add-Type magically compiles your C# code on the fly, turning your PowerShell session into a powerhouse where you can call C# classes and methods like they’ve always been there.

We didn’t stop there, we passed parameters from PowerShell to C# to make your scripts more dynamic and flexible. Plus, you saw how to compile your C# code into a DLL and load that into PowerShell for reuse and distribution

The takeaway? When PowerShell’s built-in tools don’t quite cut it, just call in the C# cavalry. Together, they give you the best of both worlds, PowerShell’s simplicity and C#’s precision, making your automation smarter, cleaner, and ready for anything.

Got questions, ideas, or cool tricks you’re cooking up with PowerShell + C#? Drop a comment or hit me up! I love geeking out over this stuff!

Until next time, keep scripting, keep experimenting, and keep leveling up. 🚀☕🍰

Leave a Reply

Your email address will not be published. Required fields are marked *