简体   繁体   English

在PowerShell cmdlet参数中声明get访问器

[英]Declare get accessors in PowerShell cmdlet parameters

According to MSDN : 根据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." “必须在公共非静态字段或属性上声明参数。应在属性上声明参数。该属性必须具有公共集访问器,如果指定了ValueFromPipeline或ValueFromPipelineByPropertyName关键字,则该属性必须具有公共get访问器。”

Why do I have to declare get accessors in my cmdlet ValueFromPipeline parameters? 为什么我必须在我的cmdlet ValueFromPipeline参数中声明get访问器? As far as I know, PowerShell only needs to put their values in, not read them out. 据我所知,PowerShell只需要将它们的值放入,而不是将它们读出来。 Thanks (by the way im just curious about this behavior :) ). 谢谢(顺便说一句,我只是好奇这个行为:))。

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 . PowerShell 分配从管道获取的新值之前, 读取使用ValueFromPipelineValueFromPipelineByPropertyName标记的参数的默认值以进行备份。

Consider the following cmdlets: 请考虑以下cmdlet:

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 New-Post cmdlet 新创建的Post对象返回具有 Title属性的管道
  • the InputObject property on the Set-Post cmdlet is marked with ValueFromPipeline = true Set-Post cmdlet上的InputObject属性标记为ValueFromPipeline = true
  • the Title property on the Set-Post cmdlet is marked with ValueFromPipelineByPropertyName = true . Set-Post cmdlet上的Title属性标记为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: 并在Set-Post cmdlet的Title属性的get访问器上设置断点会产生以下堆栈跟踪:

PowerShell中参数绑定的堆栈跟踪

As you can see, the CmdletParameterBinderController.GetDefaultParameterValue method is invoked during the process of binding the Title property on the Set-Post cmdlet with the value from the corresponding property on the object coming from the pipeline. 如您所见,在将Set-Post cmdlet上的Title属性与来自管道的对象上的相应属性的值绑定的过程中,将调用CmdletParameterBinderController.GetDefaultParameterValue方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM