Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

powershell - Run PSCmdLets in C# code (Citrix XenDesktop)

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();
        }
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...