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>
)
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With