Execute C# Code with Parameters Using PowerShell

The topic for today is a problem I spent close to two hours on last night. Surprisingly there doesn’t appear to be any easy solution on the web with most suggesting workarounds I didn’t find acceptable. To save others the time, I’d thought I’d share what I came up with here. As title of the page suggests, it’s about running C# code within PowerShell, something I’ve been doing more and more off lately. This comes about because as much as I love using C#, it is not always the best language or tool for the job and in many situations especially within the corporate environment, C# may not even be a choice (or at least there’s less resistance with PowerShell).

Despite my growing fondness for PowerShell though, I still struggle with the more complex tasks (I’ve being doing C# a lot longer) and so to save myself time, I either interpret the C# into PowerShell where I can or simply embed the C# into the PowerShell when interpreting becomes too difficult. Embedding shows the #C code as well as overcoming the need to compile.

To keep things easy, I’ll just use a simple example but which still shows the crux of what we’re trying to achieve.

The first problem you’ll encounter is when you try to run multiple executions with code changes (the embedded C#). PowerShell will through an exception that goes something like: “Cannot add type. The type name ‘xxxx’ already exists”.  The workaround I used was something I found on Adam Furmanekl’s blog.

If you go there, Adam will also show you some other useful tips if you’re just getting started. The code for this solution goes something like this below.

Execute C# Code with Parameters Using PowerShell

The other problem I had was passing parameters from PowerShell into C#. If you’re only passing in one value, this can easily be achieved using the standard Invoke-Expression. The trouble comes when you need to pass in an array of values. It is here where making the same expression dynamic helps. Below is how you would achieve that.

Execute C# Code with Parameters Using PowerShell

There you, reusing code as it’s best. Happy coding.


Leave a Reply