2

PowerShell 4.0

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

这是我的简单尝试:

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

1 回答 1

1

您的代码中有两个问题:

  1. 您需要User公开课程,以便 PowerShell 可以看到。
  2. 您应该使用AddScript而不是AddCommand.

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

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();
        }
    }
}
于 2016-01-31T13:38:07.670 回答