Interacting between Powershell and a host .NET application

An unusual topic in today’s post : interacting between Powershell and a host .NET application. The examples available on MSDN show how to host Powershell runspaces using classes from the System.Management.Automation namespace ; but it is also possible to share objects with hosted Powershell scripts paving the way to hybrid scenarios. This allows, for example, handling Exchange Management Shell objets from a .NET application.

Interactions between the .NET host and the Powershell runspaces are handled by the Runspace.SessionStateProxy property. Once the object is associated with a variable, the scripts running in the runspace are able to access it just like any other local Powershell variable.

rs.SessionStateProxy.SetVariable("myVariable", ic);

using (Pipeline pipeline = rs.CreatePipeline("$myVariable.SomeNumber = $myVariable.SomeNumber + 1"))

pipeline.Invoke();

The other way around, getting an object that was instantiated by a hosted Powershell script, is also possible and requires the following cast:

ic = (rs.SessionStateProxy.GetVariable("mySecondVariable") as PSObject).BaseObject as InstantiatedClass;

The code accompanying this post shows two-operations, modifying the property of an object and calling methods from Powershell. Please note that the example code requires a reference to the Powershell System.Management.Automation DLL.

Program.cs