Stop cmdlet after X iterations

Viewed 53

I have a cmdlet that takes pipeline values:

1..10 | Test-MyCmdlet

I want to limit Test-MyCmdLet to only process the first 5 objects (edit not by limiting the input piped to it.)

My first solution was to set a counter in the BEGIN block, increment that in the PROCESS block, and break out of the process block once it reaches a threshold. That seems a little 'hacky' to me.

Is there a better way?

The tl;dr version of how I arrived at this question is:

I have a C# module that defines a cmdlet Open-View with the following parameter

[Parameter(Position = 0, Mandatory = true, ValueFromPipeline = true)]
public IViewDef[] View {get; set;}

where IViewDef is a custom type from another assembly. The cmdlet opens windows in a 3rd party app.

IViewDef has a property called Name

I wanted to make the cmdlet a little more versatile so I changed it to this:

[Parameter(Position = 0, Mandatory = true, ValueFromPipelineByParameterName = true)] // by parameter name
public string[] Name {get; set;} // notice that this is now Name

Now I can also call it from the CLI and type my own viewnames.

This introduces a problem tho: it no longer recognizes IViewDef objects piped in. I think that is because ValueFromPipelineByParameterName expects the parameter name of the input object to be of the same signature, ergo string[].

So I changed it to:

[Parameter(Position = 0, Mandatory = true, ValueFromPipelineByParameterName = true)]
public string Name {get; set;} // no more array

That works, but there is a reason I originally defined it as an array: I wanted to be able to count the number of views being passed in and stop processing them if their number reaches a threshold. I can now no longer do that. Back to the original question.

0 Answers
Related