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?

0

1 Answer 1

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();
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.