0

PowerShell 4.0

In my application the Application class has the set of important properties, methods, and events. I want to work with that members through the app PowerShell variable (it would be like the alias of the class). But the Runspace.SessionStateProxy.SetVariable expects the instance of the class in the second parameter:

using app = CompanyName.AppName.Application;
...
using (Runspace rs = RunspaceFactory.CreateRunspace()) {
    rs.ThreadOptions = PSThreadOptions.UseCurrentThread;
    rs.Open();

    // TODO: The problem is here (app is not the instance of 
    //the Application class
    rs.SessionStateProxy.SetVariable("app", app); 

    rs.SessionStateProxy.SetVariable("docs", app.DocumentManager);

    using (PowerShell ps = PowerShell.Create()) {
        ps.Runspace = rs;

        ps.AddScript("$docs.Count");
        ps.Invoke();
    }
    rs.Close();
}

How can I do it?

Andrey Bushman
  • 11,712
  • 17
  • 87
  • 182

1 Answers1

2

You can use typeof operator in C# to get System.Type instance, which represent specified type. In PowerShell you can use static member operator :: to access to static members of some type.

using app = CompanyName.AppName.Application;
...
using (Runspace rs = RunspaceFactory.CreateRunspace()) {
    rs.ThreadOptions = PSThreadOptions.UseCurrentThread;
    rs.Open();

    rs.SessionStateProxy.SetVariable("app", typeof(app)); 

    using (PowerShell ps = PowerShell.Create()) {
        ps.Runspace = rs;

        ps.AddScript("$app::DocumentManager");
        ps.Invoke();
    }
    rs.Close();
}
user4003407
  • 21,204
  • 4
  • 50
  • 60