1

This is a very simple issue as far as I understand. There are plenty of similar questions on here, but I haven't been able to find exactly what I need. What am I missing?

Expected output

1 2 3

Actual output (error)

cmdlet ForEach-Object at command pipeline position 1
Supply values for the following parameters:
Process[0]:

Code

function processItem {
  param($item)
  Process {
    $item
  }
}

$collection = @(1,2,3)

$collection | foreach-object | processItem

1 Answer 1

5

First, you don't have to use Foreach-Object here because the pipeline will directly unwrap $items and send one value at a time to your function processItem.

Passing Arrays to Pipeline

If a function returns more than one value, PowerShell wraps them in an array. However, if you pass the results to another function inside a pipeline, the pipeline automatically "unwraps" the array and processes one array element at a time.

The parameter $item in the function doesn't accept pipeline input in your code, you should use ValueFromPipeline like this:

function processItem {
  param([parameter(ValueFromPipeline=$true)]$item)
  Process {
    $item
  }
}

Use like this:

$items = @(1, 2, 3)
$items | processItem
Sign up to request clarification or add additional context in comments.

2 Comments

I get an error Property 'AcceptValueFromPipeline' cannot be found for type 'System.Management.Automation.CmdletBindingAttribute'
Glad to help you :D Accept the answer so others can find it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.