我可以在我托管的 PowerShell 中创建变量并启动 类 的方法吗?

Can I create the variables and launch the methods of my classes in PowerShell hosted by me?

PowerShell 4.0

我想在我的应用程序中托管 PowerShell 引擎,并能够在托管的 PowerShell 中使用我的应用程序的 API。我在文档中阅读了 PowerShell class and its members 的描述。在 PowerShell.exePowerShell_ISE.exe 主机中,我可以创建变量、循环、启动我的 classes 的静态方法和实例方法。我可以通过 PowerShell class 做同样的事情吗?我找不到关于它的例子。

这是我简单的尝试:

using System;
using System.Linq;
using System.Management.Automation;

namespace MyPowerShellApp {

    class User {
        public static string StaticHello() {
            return "Hello from the static method!";
        }
        public string InstanceHello() {
            return "Hello from the instance method!";
        }
    }

    class Program {
        static void Main(string[] args) {
            using (PowerShell ps = PowerShell.Create()) {
                ps.AddCommand("[MyPowerShellApp.User]::StaticHello");
                // TODO: here I get the CommandNotFoundException exception
                foreach (PSObject result in ps.Invoke()) {
                    Console.WriteLine(result.Members.First());
                }
            }
            Console.WriteLine("Press any key for exit...");
            Console.ReadKey();
        }
    }
}

你的代码有两个问题:

  1. 您需要使 User class public 对 PowerShell 可见。
  2. 您应该使用 AddScript 而不是 AddCommand

此代码将调用 User class 的两个方法并将结果字符串打印到控制台:

using System;
using System.Management.Automation;

namespace MyPowerShellApp {

    public class User {
        public static string StaticHello() {
            return "Hello from the static method!";
        }
        public string InstanceHello() {
            return "Hello from the instance method!";
        }
    }

    class Program {
        static void Main(string[] args) {
            using (PowerShell ps = PowerShell.Create()) {
                ps.AddScript("[MyPowerShellApp.User]::StaticHello();(New-Object MyPowerShellApp.User).InstanceHello()");
                foreach (PSObject result in ps.Invoke()) {
                    Console.WriteLine(result);
                }
            }
            Console.WriteLine("Press any key for exit...");
            Console.ReadKey();
        }
    }
}