2

在 C# 中编写 cmdlet 时如何使用管道中的数据?

例如我有两个类:

这个产生数据:

[Cmdlet(VerbsCommon.Get, "Numbers")]
public class GetNumbers : Cmdlet
{
    protected override void ProcessRecord()
    {
        WriteObject(new[] {1, 2, 3, 4, 5}, true);
    }
}

而这个必须消耗这些数据:

[Cmdlet(VerbsCommon.Find, "Numbers")]
public class FindNumbers: Cmdlet
{
    protected override void ProcessRecord()
    {
        foreach (var variable in %Input%) // Where do I get input? Any ReadRecord or something else?
        {
            if (variable % 2 == 0)
            {
                WriteObject(variable);
            }
        }
    }
}

这样:

Get-Numbers | Find-Numbers
4

1 回答 1

5

您应该使用ParameterAttribute类的ValueFromPipeline :

[Cmdlet(VerbsCommon.Find, "Numbers")]
public class FindNumbers: Cmdlet
{
    [Parameter(ValueFromPipeline = true)] // The data appear in this variable
    public int[] Input { get; set; }

    protected override void ProcessRecord()
    {
        foreach (var variable in Input)
        {
            if (variable % 2 == 0)
            {
                WriteObject(variable);
            }
        }
    }
}
于 2013-01-09T16:41:19.690 回答