c# - 在 PowerShell cmdlet 参数中声明获取访问器

标签 c# powershell properties parameters pipeline

根据 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 读取标有 ValueFromPipelineValueFromPipelineByPropertyName 的参数的默认值,以在分配之前进行备份从 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 访问器上设置断点会产生以下堆栈跟踪:

Stack trace for parameter binding in PowerShell

如您所见,CmdletParameterBinderController.GetDefaultParameterValue 方法在 Set-Postcmdlet 上绑定(bind) Title 属性的过程中被调用使用来自管道的对象的相应属性的值。

关于c# - 在 PowerShell cmdlet 参数中声明获取访问器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10108221/

相关文章:

c# - 如何修复此 Esc 键错误?

PowerShell 功能和性能

configuration - 在 Scala 中处理属性

c# - 在调用新操作时帮助理解 C# 语法

c# - 我想知道在 visual studio 2010 中调试期间是否可以跳过(不运行)一行代码,

c# - 如何从 XElement 中删除特定节点?

powershell - -s 在 powershell 中使用 Start-Job 时

powershell - 使用 AssumeRole、现有策略和唯一 URL 颁发临时凭证以登录 AWS 管理控制台

c# - 迭代静态类中的属性

python - 如何将 buildbot 属性转换为字符串值