Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Script only seems to process the last object from the pipeline

I have a script that I'm trying to add pipeline functionality to. I'm seeing the strange behavior, though, where the script seems to only be run against the final object in the pipeline. For example

param(
  [parameter(ValueFromPipeline=$true)]
  [string]$pipe
)

foreach ($n in $pipe) {
  Write-Host "Read in " $n
}

Dead simple, no? I then run 1..10 | .\test.ps1 and it only outputs the one line Read in 10. Adding to the complexity, the actual script I want to use this in has more to the parameters:

[CmdletBinding(DefaultParameterSetName="Alias")]
param (
  [parameter(Position=0,ParameterSetName="Alias")]
  [string]$Alias,

  [parameter(ParameterSetName="File")]
  [ValidateNotNullOrEmpty()]
  [string]$File

  <and so on>
)
like image 504
ASTX813 Avatar asked Jan 09 '13 19:01

ASTX813


People also ask

What is $_ in PowerShell?

The “$_” is said to be the pipeline variable in PowerShell. The “$_” variable is an alias to PowerShell's automatic variable named “$PSItem“. It has multiple use cases such as filtering an item or referring to any specific object.

What is InputObject in PowerShell?

InputObject is a generic name used for a parameter that takes pipeline input. It's part of internal PowerShell naming convention and there is nothing special about it.

What is pipeline function in PowerShell?

Pipeline-aware functions unleash the real flexibility of PowerShell command composition. One of the most powerful features of PowerShell is its ability to combine commands via the pipeline operator. With just very little coding effort, your own PowerShell functions can support pipeline input, too.


1 Answers

You need to wrap the main body of the script with process{}, this will then allow you to process each item on the pipeline. As process will be called for each item you can even do away with the for loop.

So your script will read as follows:

param(
  [parameter(ValueFromPipeline=$true)]
  [string]$pipe
)
process
{
      Write-Host "Read in " $pipe
}

You can read about input processing here: Function Input Processing Methods

like image 140
David Martin Avatar answered Oct 20 '22 01:10

David Martin