Declare get accessors in PowerShell cmdlet parameters

According to MSDN:

"Parameters must be declared on public non-static fields or properties. Parameters should be declared on properties. The property must have a public set accessor, and if the ValueFromPipeline or ValueFromPipelineByPropertyName keyword is specified, the property must have a public get accessor."

Why do I have to declare get accessors in my cmdlet ValueFromPipeline parameters? As far as I know, PowerShell only needs to put their values in, not read them out. Thanks (by the way im just curious about this behavior :) ).

Answers


PowerShell reads the default value of the parameters marked with ValueFromPipeline or ValueFromPipelineByPropertyName to make a backup before assigning the new value obtained from the pipeline.

Consider the following cmdlets:

New-Post -Title <string>
Set-Post -InputObject <Post> -Title <string>

where the following applies:

  • the New-Post cmdlet returns the newly created Post object to the pipeline, which has a Title property
  • the InputObject property on the Set-Post cmdlet is marked with ValueFromPipeline = true
  • the Title property on the Set-Post cmdlet is marked with ValueFromPipelineByPropertyName = true.

Combining them with the following command:

New-Post -Title "Foo" | Set-Post

and setting a breakpoint on the get accessor of the Set-Post cmdlet's Title property results in the following stack trace:

As you can see, the CmdletParameterBinderController.GetDefaultParameterValue method is invoked during the process of binding the Title property on the Set-Postcmdlet with the value from the corresponding property on the object coming from the pipeline.


Need Your Help

Access Datagrid row on TemplateColumn button click

silverlight datagrid datagridtemplatecolumn

I am implementing a file upload tool using Silverlight. In this I can browse for files and when I select a file then it is bound to a datagrid. In the datagrid I have a template column with a butto...

Whats wrong in my xsd schema ? It gives type element is not declared on include of another xsd file

c# xml xsd xsd-validation xml-validation

I am trying to validate a xml using schema but the problem is xsd is not valid, i tried ti tested if it valid or not, it gives error XSD schema Error: Type 'testNamespaces:eltyp_string035' is not