【问题标题】:How can I get the original pipeline object when using ValueFromPipelineByPropertyName?使用 ValueFromPipelineByPropertyName 时如何获取原始管道对象?
【发布时间】:2018-06-17 14:37:33
【问题描述】:

我正在用 C# 构建一个 Cmdlet。

当使用ValueFromPipelineByPropertyName=true 绑定参数时,我经常想将绑定属性的原始管道对象传递回管道。如何获得对这个原始对象的引用?

如果这是我的 cmdlet

[Cmdlet(VerbsLifecycle.Start, "Foo")]
public class StartFooCommand : PSCmdlet
{
    [Parameter(Position = 0, Mandatory = true, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true)]
    public String Name { get; set; }

    protected override void ProcessRecord()
    {
        // Perform various Foo-related activities...

        Object pipelineObject = GetTheObjectPassedInFromThePipeline();

        WriteObject(pipelineObject);
    }
}

我希望能够在我的脚本中做到这一点

# $foo would be some return value from another cmdlet
$foo = New-Object PSObject -prop @{ Name = "Frank"; Bar = "Baz" }
$foo | Get-Foo | Use-Foo
#    ^         ^ Here I want to pass the original $foo object to the next cmdlet
#    L Name gets bound from my object to my property

【问题讨论】:

  • 发布一些相关的代码来展示你的需求。

标签: c# powershell cmdlets cmdlet pscmdlet


【解决方案1】:

您只需要包含另一个具有 ValueFromPipeline=$true 属性的参数。

【讨论】:

  • 太棒了!我从来没有想过管道对象本身除了绑定到其他参数的属性之外,还会绑定到一个参数。
  • 我通常不这样做,但它确实有效。 :-)
  • 我怀疑很多人都这样做。我敢肯定这都是一个糟糕的主意,但我对 PS 的经验还不够,无法识别以后肯定会咬我的东西;)
  • 这不是一个糟糕的主意,我不认为,但我从来没有真正需要这样做。一些内置命令允许通过 -Passthru 开关输出原始对象,但仅使用 ValueFromPipelineByPropertyName 来实现这一点非常困难。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-07-15
  • 1970-01-01
  • 2022-11-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-03
相关资源
最近更新 更多