Context
I have a C# application with a GUI for standard users, but for advanced users I want to provide a command line that will allow to manipulate all objects in the app. My idea is to use powershell for that. If I can run the powershell engine inside my app and I can give this engine a variable that is the root object of my app, then if I can get a powershell console to connect to the hosted engine in my app, then I could do whatever I want. That would allow me to provide powerfull command line for my advanced users.
Trials
I have read that powershell engine is hostable so my understanding is that I can run the engine "in process" so It could access my objects without marshalling. I came up with this code to start the powershell engine.
using System.Management.Automation.Runspaces;
namespace ConsoleApp1
{
public class Program
{
public double A = 10;
public string B = "toto";
static void Main(string[] args)
{
var ist = InitialSessionState.Create();
ist.Variables.Add(new SessionStateVariableEntry("root", new Program(), "root object"));
var r = RunspaceFactory.CreateRunspace(ist);
r.Open();
Console.ReadLine();
}
}
}
That effectively starts the powershell engine, and then I can connect using the powershell console.
PS C:\Users\Lionel> Enter-PSHostProcess consoleapp1
[Processus :23788]: PS C:\Users\Lionel\Documents> dir variable:
I get a console connected to my app but I don't see my root variable. If I enumerate the runspaces in the host process like that:
[Processus :23788]: PS C:\Users\Lionel\Documents> get-runspace
Id Name ComputerName Type State Availability
-- ---- ------------ ---- ----- ------------
1 Runspace1 localhost Local Opened Available
2 RemoteHost localhost Local Opened Busy
I see 2 runspaces, the first one is the one I started and the second one is the one that has been created when I connected the powershell console. If I look into the first runspace like that:
[Processus :23788]: PS C:\Users\Lionel\Documents> (get-runspace -id 1).SessionStateProxy.GetVariable("root")
A B
- -
10 toto
I clearly see my root variable.
Questions
So my problem is, how do I connect my powershell console to the first runspace and not to create a new one ? Or, alternatively, how do I force the variables I want into the runspace that are created by remote sessions ?