Accepting Multiple Input

by Jul 11, 2014

All PowerShell versions

When you create PowerShell functions, here is a template that defines a InputObject parameter that will accept multiple values both via parameter and via pipeline:

function Get-Something
{
  param
  (
    [Parameter(Mandatory=$true,ValueFromPipeline=$true)]
    [Object[]]
    $InputObject 
  )
  
  process
  {
    $InputObject | ForEach-Object {
      $element = $_
      "processing $element"
    }
  }
}

And this is what the function does in action:

PS> Get-Something -InputObject 1,2,3,4
processing 1
processing 2
processing 3
processing 4

PS> 1,2,3,4 | Get-Something
processing 1
processing 2
processing 3
processing 4

Note how the parameter is defined as an object array (so it can accept multiple values). Next, the parameter value runs through ForEach-Object to process each element individually. This takes care of the first example call: assigning comma-separated (multiple) values.

To be able to accept multiple values via pipeline, make sure you assign ValueFromPipeline to the parameter that is to accept pipeline input. Next, add a Process script block to your function. It serves as a loop, very similar to ForEach-Object, and runs for each incoming pipeline item.

Twitter This Tip! ReTweet this Tip!