在C#代码中运行PSCmdLets(Citrix XenDesktop)

我是PowerShell的新手,在C#中运行PowerShell cmd-lets。 具体来说,我正在尝试使用Citrix的XenDesktop SDK编写Web应用程序来管理我们的XenDesktop环境。

就像快速测试一样,我提到了Citrix BrokerSnapIn.dll,看起来它给了我很好的C#类。 但是,当我使用此错误消息命中.Invoke时:“无法直接调用从PSCmdlet派生的Cmdlet。”

我搜索并尝试了一堆东西,但不知道如何调用PSCmdlets。 我有点想到我必须使用字符串和运行空间/管道等来做到这一点。

谢谢高级,NB

using System; using System.Management.Automation; using System.Management.Automation.Runspaces; using Citrix.Broker.Admin.SDK; namespace CitrixPowerShellSpike { class Program { static void Main(string[] args) { var c = new GetBrokerCatalogCommand {AdminAddress = "xendesktop.domain.com"}; var results = c.Invoke(); Console.WriteLine("all done"); Console.ReadLine(); } } } 

您需要托管PowerShell引擎才能执行PSCmdlet,例如(来自MSDN文档 ):

  // Call the PowerShell.Create() method to create an // empty pipeline. PowerShell ps = PowerShell.Create(); // Call the PowerShell.AddCommand(string) method to add // the Get-Process cmdlet to the pipeline. Do // not include spaces before or after the cmdlet name // because that will cause the command to fail. ps.AddCommand("Get-Process"); Console.WriteLine("Process Id"); Console.WriteLine("----------------------------"); // Call the PowerShell.Invoke() method to run the // commands of the pipeline. foreach (PSObject result in ps.Invoke()) { Console.WriteLine( "{0,-24}{1}", result.Members["ProcessName"].Value, result.Members["Id"].Value); } }