PowerShell 4.0
我想在我的应用程序中托管 PowerShell 引擎,并能够在托管的 PowerShell 中使用我的应用程序的 API。我阅读了 PowerShell class 的描述及其 members在文档中。在 PowerShell.exe
和 PowerShell_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();
}
}
}
最佳答案
你的代码有两个问题:
- 您需要将
User
类公开,以便 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();
}
}
}
关于c# - 我可以在我托管的 PowerShell 中创建变量并启动我的类的方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35111921/