【问题标题】:How can I create the PowerShell variables for working with the static members?如何创建用于处理静态成员的 PowerShell 变量?
【发布时间】:2016-05-09 06:37:42
【问题描述】:

PowerShell 4.0

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

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# powershell powershell-4.0 powershell-hosting


    【解决方案1】:

    您可以在 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();
    }
    

    【讨论】:

      猜你喜欢
      • 2013-09-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-23
      • 1970-01-01
      相关资源
      最近更新 更多