Run PSCmdLets in C# code (Citrix XenDesktop)

匿名 (未验证) 提交于 2019-12-03 00:59:01

问题:

I'm new to PowerShell and running PowerShell cmd-lets in C#. Specifically, I'm trying to use Citrix's XenDesktop SDK to write a web app to manage our XenDesktop environment.

Just as a quick test, I made a reference to the Citrix BrokerSnapIn.dll, which looks like it gives me good C# classes. However, when I hit the .Invoke with this error message: "Cmdlets derived from PSCmdlet cannot be invoked directly."

I've searched and tried a bunch of stuff, but don't know how to call PSCmdlets. I'm kinda left thinking that I have to use strings and a runspace/pipeline, etc, to do this.

Thanks In Advanced, 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();         }     } } 

回答1:

You need to host the PowerShell engine in order to execute a PSCmdlet e.g. (from the MSDN docs):

  // 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);   }  }  


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!