根据 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."
为什么我必须在我的 cmdlet ValueFromPipeline
参数中声明 get 访问器?据我所知,PowerShell只需要把它们的值放进去,不需要读出来。谢谢(顺便说一句,我只是对这种行为感到好奇 :))。
最佳答案
PowerShell 读取标有 ValueFromPipeline
或 ValueFromPipelineByPropertyName
的参数的默认值,以在分配之前进行备份从 the pipeline 获得的新值.
考虑以下 cmdlet:
New-Post -Title <string>
Set-Post -InputObject <Post> -Title <string>
以下情况适用:
New-Post
cmdlet 返回新创建的Post
对象到管道,有标题
属性Set-Post
cmdlet 上的InputObject
属性标记为ValueFromPipeline = true
Set-Post
cmdlet 上的Title
属性标有ValueFromPipelineByPropertyName = true
。
将它们与以下命令组合:
New-Post -Title "Foo" | Set-Post
并在 Set-Post
cmdlet 的 Title
属性的 get 访问器上设置断点会产生以下堆栈跟踪:
如您所见,CmdletParameterBinderController.GetDefaultParameterValue
方法在 Set-Post
cmdlet 上绑定(bind) Title
属性的过程中被调用使用来自管道的对象的相应属性的值。
关于c# - 在 PowerShell cmdlet 参数中声明获取访问器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10108221/