从管道中获取数据

时间:2013-01-09 16:40:40

标签: c# powershell pipeline

在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

1 个答案:

答案 0 :(得分:5)

您应该使用ValueFromPipeline类的ParameterAttribute

[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);
            }
        }
    }
}