13

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>
)
ASTX813
  • 313
  • 3
  • 13

1 Answers1

17

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

David Martin
  • 11,764
  • 1
  • 61
  • 74
  • That worked in my simple test script above, but when I put it in my script, it actually runs Get-Process (and fails because it's receiving a script block for the Name parameter) – ASTX813 Jan 09 '13 at 19:57
  • Can you put your full script or at least the salient parts in your question? – David Martin Jan 09 '13 at 20:02
  • Since my development box is refusing to allow me to copy and paste, I'm not going to be able to pull that off. I can tell you I tried adding more complexity to the test script and found the trigger. When I added `function something { Write-Host "functioning" }` before the process{} block in the test script, it did the same thing. If I wrap the whole block in process{}, though, the test script works. – ASTX813 Jan 09 '13 at 20:09
  • If I understand correctly your script also contains functions, what I tend to do is put the functions in the begin block. – David Martin Jan 09 '13 at 20:12
  • 3
    Yep, that did the trick. I guess if you use a process{} block, the whole script body has to be in it or begin and end blocks. Thanks! – ASTX813 Jan 09 '13 at 20:16