Quantcast
Channel: Windows PowerShell forum
Viewing all articles
Browse latest Browse all 21975

refactored and older 'filter' into an 'advanced function' - question

$
0
0

Hello,

I have a 'filter' I wrote back in PS v1 days and have a renewed use for it, so I'm refactoring it using the advanced functions method... it worked as a filter, but as an advanced function was getting "The input object cannot be bound to any parameters for the command either because the command does not take pipeline input or the input and its properties do not match any of the parameters that take pipeline input." error.

basic structure as a filter was:

filter ExampleFilter
{
	param(
		[string]$someParam, 
		[string]$SomeRequiredParam  = $(throw 'You must supply the SomeRequiredParm parameter'
		[string]$AnotherRequiredParam = $(throw 'You must supply the AnotherRequired parameter')	
	)
	#code here, not important, but note I just used $_ to access each item passed in from the pipeline... and it works fine
}

In that example, I used $_ to access each item passed in from the pipeline... also note all three of the defined parameters are NOT the input from the pipeline, they all modify processing behavior of the function, but the function (filter) processed input from the pipeline.

Now, I refactored like so:

function ExampleAdvancedFunction
{
	[CmdletBinding()]
    param
    (
        [Parameter(Mandatory=$true, Position=0)] [Alias("p1")] [string] $Param1  = $(throw 'You must supply the Param1 parameter'),
        [Parameter(Mandatory=$true, Position=1)] [Alias("p2")] [string] $Param2 = $(throw 'You must supply the Param2 parameter'),	
        [string]$AnotherParam	
	)
    BEGIN
    {     
    }

    PROCESS
    {
        # same as filter example, but never runs do to parameter binding error
    }

    END
    {       
    }

when I pipe input to this second function I get the error about not being able to bind parameters.

If I add this as my first param:

[Parameter(ValueFromPipeline=$true)]$InputObject

It then works as expected...

1. why? what was the 'filter' syntax doing differently?

2. I'm still using $_ to process the pipeline input in the PROCESS block, so having that $InputObject param seems superfluous, as I don't ever use it in the code... it's obviously just make PS able to bind params correctly.

Just kind of curious about this... could anyone explain?

thanks!


Viewing all articles
Browse latest Browse all 21975

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>