Run PSCmdLets in C# code (Citrix XenDesktop)
Asked Answered
S

1

2

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.

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();
        }
    }
}
Somite answered 3/10, 2012 at 15:52 Comment(0)
G
6

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);
  } 
} 
Garment answered 3/10, 2012 at 16:27 Comment(2)
Hi Keith, thanks for the answering. I saw that article (and to be honest, was trying to avoid the "magic string" like "Get-Process". In the Citrix SDK, the object browser shows a GetBrowserCatalogCommand like above so that I can take advantage of the strongly-typed class. Looks like I'm going down your route, tho.Somite
Yeah the primary difference between a cmdlet deriving from S.M.A.Cmdlet and one deriving from S.M.A.PSCmdlet is that the former can be used in isolation i.e. without loading the PowerShell engine and the latter cannot.Garment

© 2022 - 2024 — McMap. All rights reserved.