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

标签 c# powershell powershell-4.0 powershell-hosting

PowerShell 4.0

我想在我的应用程序中托管 PowerShell 引擎,并能够在托管的 PowerShell 中使用我的应用程序的 API。我阅读了 PowerShell class 的描述及其 members在文档中。在 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();
        }
    }
}

最佳答案

你的代码有两个问题:

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

关于c# - 我可以在我托管的 PowerShell 中创建变量并启动我的类的方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35111921/

相关文章:

c# - 防止密码泄露(GetNetworkCredential 方法)

azure - SB 队列的 PowerShell New-AzureSBAuthorizationRule 返回“对象未设置为对象的实例”

C# WPF - ListView 绑定(bind)不起作用

c# - 在 Windows 服务中使用 Rx

json - 具有/JSON正文的Powershell Invoke-Webrequest-无法反序列化吗?

powershell - 按大小对所有文件夹中的所有文件进行排序

c# - 捕获的正则表达式超出预期

c# - 如何在 WCF 客户端代理中公开的接口(interface)中声明事件?

powershell - 如何检查 PowerShell 开关参数是否不存在或错误

powershell - 使用 Get-ChildItem -Exclude 或 -Include 不返回任何内容