Using ValueFromPipeline for multiple parameters

If more than one parameter uses ValueFromPipeline, PowerShell will attempt to provide values to each. The parameter binder can be said to be greedy in this respect. The following function can be used to show that both parameters are filled with the same value if the parameters accept the same type, or if the value can be coerced into that type:

function Test-ValueFromPipeline {
[CmdletBinding()]
param (
[Parameter(ValueFromPipeline)]
[Int]$Parameter1,

[Parameter(ValueFromPipeline)]
[Int]$Parameter2
)

process {
'Parameter1: {0}:: Parameter2: {1}' -f $Parameter1, $Parameter2
}
}

Providing an input pipeline for the command shows the values assigned to each parameter:

PS> 1..2 | Test-ValueFromPipeline
Parameter1: 1 :: Parameter2: 1
Parameter1: 2 :: Parameter2: 2

Filling variables is the job of the parameter binder in PowerShell. Using Trace-Command will show the parameter binder in action:

Trace-Command -Expression { 1 | Test-ValueFromPipeline } -PSHost -Name ParameterBinding

The bind-pipeline section will display messages that show that the value was successfully bound to each parameter. If the two parameters expected different types, the parameter binding will attempt to coerce the value into the requested type. If that is not possible, it will give up on the attempt to fill the parameter. The next example declares two different parameters; both accept values from the pipeline and neither is mandatory:

function Get-InputObject {
[CmdletBinding()]
param (
[Parameter(ValueFromPipeline)]
[System.Diagnostics.Process]$ProcessObject,

[Parameter(ValueFromPipeline)]
[System.ServiceProcess.ServiceController]$ServiceObject
)

process {
if ($ProcessObject) { 'Process: {0}' -f $ProcessObject.Name }
if ($ServiceObject) { 'Service: {0}' -f $ServiceObject.Name }
}
}

The command will, at this point, accept pipeline input from both Get-Process and Get-Service. Each command will fill the matching parameter, Get-Process fills ProcessObject, and Get-Service fills ServiceObject. This design is unusual and perhaps confusing; here, it is only demonstrated because it is possible. A parameter set can be used to make sense of the pattern, which we will explore in the Defining parameter sets section.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.128.30.77