2

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
CJBS
  • 15,147
  • 6
  • 86
  • 135
Vitaliy
  • 702
  • 6
  • 19

1 Answers1

5

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);
            }
        }
    }
}
Vitaliy
  • 702
  • 6
  • 19
  • This might also help : http://stackoverflow.com/questions/885349/how-to-write-a-powershell-script-that-accepts-pipeline-input – Zasz Jan 09 '13 at 16:44
  • 4
    @Zasz: I do not see how your link is related to writing these cmdlets in C#? – mousio Jan 10 '13 at 21:48