如何创建用于处理静态成员的 PowerShell 变量?

How can I create the PowerShell variables for working with the static members?

PowerShell 4.0

在我的应用程序中,Application class 具有一组重要的属性、方法和事件。我想通过 app PowerShell 变量与该成员一起工作(它就像 class 的别名)。但是 Runspace.SessionStateProxy.SetVariable 期望第二个参数中 class 的实例:

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();
}

我该怎么做?

您可以在C#中使用typeof运算符来获取System.Type实例,它表示指定的类型。在 PowerShell 中,您可以使用静态成员运算符 :: 来访问某种类型的静态成员。

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();
}