2

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

作为一个快速测试,我参考了 Citrix BrokerSnapIn.dll,它看起来给了我很好的 C# 类。但是,当我点击 .Invoke 并显示以下错误消息时:“不能直接调用从 PSCmdlet 派生的 Cmdlet。”

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

感谢先进,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();
        }
    }
}
4

1 回答 1

6

您需要托管 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);
  } 
} 
于 2012-10-03T16:27:01.683 回答