Embed a C# Program in a PowerShell Script

Advanced Event 8 of the 2011 Scripting Games was a beast. It was complex even before the requirement of writing a graphical user interface, and this event had the lowest number of submissions out of all the events.

Many opted to use Sapien’s PrimalForms tool along with some community modules to handle the image manipulation. I decided to go a different route and code the entire program in C# and then embed that program in a PowerShell script. PowerShell can do just about anything, but when it comes to writing a complex GUI, I prefer to fire up Visual Studio. It also helps to be able to directly use examples of C# code to solve some of the problems without having to convert it to PowerShell code.

After everything was working the way I wanted it in Visual Studio, all of the code was pasted into a huge here-string in my script.

When using Windows Presentation Foundation classes, it’s important to make sure PowerShell is running in a Single Threaded Apartment (STA).

The Add-Type cmdlet is then used to import the source code. The ReferencedAssemblies parameter makes sure all of our using directives can find the assemblies they need. Then a new object is created, Form1 in this case, and we start it with the ShowDialog method.

Convert Image

All of my entries for the 2011 Scripting Games can be found at PoshCode.

Complete Script: