PowerShell – Global variables and Constant sharing between PowerShell and C#

Recently I came across this situation where I wanted a variable to be available in C# context and as well as in the PowerShell runspace. This was important as it would make the solution way more simpler.

I used two features to make this possible

  1. Global Variables from PowerShell
  2. Static classes in .Net
  3. You can compile the .net code at runtime in PowerShell and use the compiled type directly or put it in a dll and load it to use it

The 3rd point allowed me to have scriptable c# code that we can alter by just opening the PS1 file and that’s it the PowerShell will take care of the compilation at the runtime so we had almost no build issues, although sometimes it becomes tricky to debug the issues. We avoided this by having many Unit test to check for any bugs/inconsistencies in the code.

Other problem I faced was the UI, the solution required a Win Form UI that was complex, in order to do that I created the WinForm code in a dll, then loaded the dll into PowerShell runspace and used the object to create the WinForm UI, so the UI logic was in C# while the automation logic was in PowerShell. I exposed the Event Handlers and data variables as properties in the WinForm code so there was no plumbing required in the PowerShell code making it cleaner. Letting the event handlers created in PowerShell allowed me to have complete control of the WinForm UI in the most abstract way.

I am not putting the code here as of now as “I am too lazy to remove the confidential code” and more importantly the methods described here can be done very easily without seeing actual code, but I will put up some code by tomorrow.

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>