PowerShell 4.0
我想在应用程序中托管PowerShell引擎,并希望能够在托管PowerShell中使用我的应用程序的API。我在文档中阅读了PowerShell类及其成员的说明。在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();
}
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句