PowerShell

PowerShell: Creating functions that accept Pipeline Input

So you have already created a function and now you want to enable pipeline functionality? Yes? Then read on. In this blog post I will show you an example on how to build functions that accept pipeline input. Let’s dive in.

Goal

Everything we want to achieve can be seen in this screenshot. Our Function Test-PipelineInput accepts objects that passes the PowerShell pipeline. This feature is called PipelinInput.

Creating an Advanced Function that accepts Pipeline Input

Here is an example on how to achieve this.

function Test-PipelineInput {

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

Begin {}

Process {
Write-Host "$Text"
}

End {}
}

The most important thing is the code block with Begin, Process and End. You need this code snippet to enable Pipeline Input. Additionally, you need to add the pipeline statement in line 5.

Wrapping up:

  • Add Begin, Process and End
  • Enter the parameter definition ValueFromPipline=$true

Important information

But wait a minute, someone says that this also works without Begin, Process and End. Well, this person is wrong. I will show you why.

Suppose the following code without Begin, Process and End.

# This code is wrong!

function Test-PipelineInput {

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

    Write-Host "$Text"
    
    }

This function creates the following output:

It’s all good. This is proof that it can be done without the Begin, Process and End blocks. Not at all.

Consider the following scenario:

Ups. Where did the first statement go? It’s not displayed. Why?

If you do not use Begin, Process, and End, PowerShell considers objects that have passed through the pipeline as objects that refer to the end block. For this reason, the first statement is not displayed.

The situation is different for our first and correct function:

What was to be shown. See you next time.

Do you like the sayings that have passed the Pipeline?

Well then, all 6 rules of success can be downloaded with the code below. They might help you moving up in your career.

Start-BitsTransfer `
-Source https://patrick6649.files.wordpress.com/2018/05/arnolds-6-rules-of-success.jpg `
-Destination (Join-Path -Path $home -ChildPath Downloads)
Start-Process (Join-Path -Path $home -ChildPath Downloads\arnolds-6-rules-of-success.jpg)

😉

Categories: PowerShell

Tagged as: ,

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 )

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.