PowerShell

PowerShell: Creating Functions that accept Pipeline Input (ByValue)

You probably have already created your first function in PowerShell and now you want that your function is capable of pipeline input. Right? Ok, you’ve come to the right place. In this blog post I will carry out creating a sample function that accepts pipeline input by value.

Sample Function

Let’s take this sample function for our experiment. It has a single parameter called “Text”.


function Test-PipelineInput {

param
(

[Parameter()]
$Text
)

Write-Host "$Text"

}

Once executed, it writes the text entered in the Text parameter, as expected.

Unbenannt.PNG

However, if you try to pipe the text of the left side of the pipe to the right side of the pipe you will be faced with an error message.

Unbenannt.PNG

The error message says:

Test-PipelineInput : 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.

ValueFromPipeline=$true

So, we have to configure our parameter to accept pipeline input. The code looks now like this:


function Test-PipelineInput {

param
(

[Parameter(ValueFromPipeline=$true)]
$Text
)

Write-Host "$Text"
}

This works out fine.

Unbenannt.PNG

What will happen if we enter two different texts?

Unbenannt.PNG

Only the second text is processed via the pipeline. Why?

Because a function that has no process statement is always an END function, that means only the second object (Hello World2) will be sent through the pipeline.

If you are wondering what ByValue means, see here: Understanding PowerShell Pipeline Parameter Binding

Must have: Begin – Process – End

Our final, working function then looks like the example below. Keep in mind, that we have no begin and no end code, therefore I decided to leave both statements empty. Remember that they are mandatory for pipeline functionality.


function Test-PipelineInput {

param
(

[Parameter(ValueFromPipeline=$true)]
$Text
)

Begin {}

Process {

Write-Host "$Text"

}

End {}

}

Unbenannt.PNG

That looks fine. It’s all good.

See you next time with PowerShell!

Categories: PowerShell

1 reply »

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.