Vitaliy Vitaliy - 2 months ago 20
C# Question

Consume data from pipeline

How to consume data from pipeline when writing cmdlets in C#?

For example I have two classes:

This one produces data:

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


And this one must consume this data:

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


In this way:

Get-Numbers | Find-Numbers

Answer

You should use ValueFromPipeline of ParameterAttribute class:

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