Parameter ValueFromPipelineByPropertyName Arguement


A customer pointed out that ValueFromPipelineByPropertyName wasn’t working as expected in one of their scripts.

I wrote a very simple code sample to demonstrate what the syntax should look like and to show the functionality in action.

Hang on, I’m getting ahead of myself…

Param ([parameter(ValueFromPipelineByPropertyName=$true)]
[String[]]$MachineName)

The Param() statement let’s us define parameters for a script or function. We can also supply arguments to the parameter attribute. In the above example, mandatory ensures that that particular parameter must be used. ValueFromPipelineByPropertyName allows us to send a value to this parameter from pipeline input, e.g. a piped CSV file – we can map properties from the CSV to corresponding parameters by using the property name.

Imagine I have a CSV file that has a column header called ‘MachineName‘. If I send the objects generated from importing that CSV down the pipeline, I can automatically bind all the entries in the MachineName column to the MachineName parameter, by using the ValueFromPipelineByPropertyName arguement.

Here’s the simple function I put together to demonstrate this in action.

function test-binding {

[CmdletBinding()]
Param(
      #The target domain
      [parameter(Mandatory,ValueFromPipelineByPropertyName,Position=0)]
      [String]$Domain,

      #The original UPN suffix, e.g. "@halo.net"
      [parameter(Mandatory,ValueFromPipelineByPropertyName,Position=1)]
      [String]$OldUpn,

      #The new UPN suffix, e.g. "@contoso.com"
      [parameter(Mandatory,ValueFromPipelineByPropertyName,Position=2)]
      [String]$NewUpn

      )
      
      process {
      
      Write-Output $Domain,$OldUpn,$NewUpn

      }
}

 

Now, let’s look at a sample, simple CSV file.

Capture159

 

We have three columns, three headers. The three headers correspond to the three parameters defined in the function, i.e. the property name and the parameter name are the same. All three parameters can accept values by property names. Let’s see what happens when we run the function.

Capture160

 

Remember that ‘Write-Output $Domain,$OldUpn,$NewUpn’ statement in the process{} block? Well it’s showing us values have been bound to the functions parameters. As you can see, for each line from the file we get $Domain, $OldUpn, $NewUpn in turn.

 

Comments (0)

Skip to main content