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

C# 我可以在我托管的PowerShell中创建变量并启动类的方法吗?,c#,powershell,powershell-4.0,powershell-hosting,C#,Powershell,Powershell 4.0,Powershell Hosting,PowerShell 4.0 我希望在我的应用程序中托管PowerShell引擎,并能够在托管的PowerShell中使用我的应用程序的API。我阅读了文档中对及其的描述。在PowerShell.exe和PowerShell_ISE.exe主机中,我可以创建变量、循环,启动类的静态和实例方法。我可以通过PowerShell类执行同样的操作吗?我找不到关于它的例子 这是我的简单尝试: 使用系统; 使用System.Linq; 使用系统、管理、自动化; 命名空间MyPowerShellApp{ 类用

PowerShell 4.0

我希望在我的应用程序中托管PowerShell引擎,并能够在托管的PowerShell中使用我的应用程序的API。我阅读了文档中对及其的描述。在
PowerShell.exe
PowerShell_ISE.exe
主机中,我可以创建变量、循环,启动类的静态和实例方法。我可以通过
PowerShell
类执行同样的操作吗?我找不到关于它的例子

这是我的简单尝试:

使用系统;
使用System.Linq;
使用系统、管理、自动化;
命名空间MyPowerShellApp{
类用户{
公共静态字符串StaticHello(){
返回“Hello from the static method!”;
}
公共字符串InstanceHello(){
返回“Hello from the instance method!”;
}
}
班级计划{
静态void Main(字符串[]参数){
使用(PowerShell ps=PowerShell.Create()){
ps.AddCommand(“[MyPowerShellApp.User]::StaticHello”);
//TODO:这里我得到了CommandNotFoundException异常
foreach(PSObject结果为ps.Invoke()){
Console.WriteLine(result.Members.First());
}
}
Console.WriteLine(“按任意键退出…”);
Console.ReadKey();
}
}
}

您的代码中有两个问题:

  • 您需要将
    用户
    类公开,以便PowerShell可见
  • 您应该使用
    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();
            }
        }
    }