【问题标题】:Invoke powershell cmdlets in pipeline in C#在 C# 的管道中调用 powershell cmdlet
【发布时间】:2022-03-17 08:50:45
【问题描述】:

System.Management.Automation.Runspaces 中的 Pipeline.Invoke 是在管道中调用 Commands 集合中存在的 cmdlet,还是在 C# 中单独执行?

我已将两个 cmdlet 添加到管道并调用 Pipeline.Invoke,但是第一个 cmdlet 的输出未被识别为管道输入,并且出现与缺少第二个 cmdlet 的必填字段相关的错误。

我们能否像在 PowerShell console A | B 中那样在 C# 中实现管道调用?

【问题讨论】:

    标签: c# powershell pipeline powershell-cmdlet


    【解决方案1】:

    管道可以执行多个命令,例如使用管道运算符|

    Commands 属性中向管道添加多个命令就足够了,例如pipeline.Commands.Add(myCmd).Add(myPipedCmd);

    例如运行Get-Item | Select Name

    Runspace runspace = RunspaceFactory.CreateRunspace();
    runspace.Open();
    Pipeline pipeline = runspace.CreatePipeline();
    Command dir = new Command("Get-Item");
    pipeline.Commands.Add(dir);
    Command select = new Command("Select");
    select.Parameters.Add(null, "Name");
    pipeline.Commands.Add(select);
    var out1 = pipeline.Invoke();
    // ...
    runspace.Close();
    

    【讨论】:

      猜你喜欢
      • 2020-02-27
      • 2013-06-08
      • 2018-12-14
      • 2014-02-28
      • 1970-01-01
      • 2018-12-17
      • 2020-06-27
      • 2014-02-11
      • 1970-01-01
      相关资源
      最近更新 更多