Quick tip: Determine if input comes from the pipeline or not

Usually you shouldn’t need to know whether data input comes from the pipeline or a parameter, but in case you are in a position where you really need to know, this post will show you a quick and easy way of determining this.

Using the built-in variable PSCmdlet you can get hold of the InvocationInfo object. This object have several useful properties, but the one we are interested in, are called ExpectingInput.

This property will be set to True if it expects input from the pipeline. We can take advantage of this to check if data is coming in from the pipeline or not.

Consider the following code:

function Invoke-Test {
    [CmdletBinding()]
    param (
        [Parameter(ValueFromPipeline)]
        [PSObject[]] $InputObject,

        [Parameter()]
        [string] $SecondParam
    )

    if ($PSCmdlet.MyInvocation.ExpectingInput) {
        "Data received from pipeline input: '$($InputObject)'"
    }

    else {
        "Data received from parameter input: '$($InputObject)'"
    }
}

Here we see that I have used a simple branch using ExpectingInput as the branching point. If it’s true, then data is coming in from the pipeline, and if it’s false, assume data comes from the parameter instead.

But be careful, as the code is above, it will execute the else-clause even if the function is called without getting input from either the pipeline or a parameter. So additional code logic is advisable if using this in a production script.

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 )

Facebook photo

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

Connecting to %s