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();
}
}
}
答案 0 :(得分:1)
您的代码中存在两个问题:
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();
}
}
}