Is it possible to attach an event to a PSObject?

允我心安 提交于 2019-12-02 01:59:13
Richard

Rather than making value a NoteProperty make it a ScriptProperty, this includes defining separate get and set methods that are called rather than directly modifying a field.

$theObject | Add-Member -MemberType ScriptProperty -Name 'Value' 
                        -Value{ $this._value }
                        -SecondValue { $this._value = $args[0]; $this.Sqrt }

(Value defines the get method, SecondValue the set.)

Note as PowerShell doesn't provide any ability to encapsulate data, the underlying field is still accessible to callers. Coding a custom type in C# (or other .NET language) and use of Add-Type can avoid this, but is unlikely to be worth it unless you really have callers who will not follow the rules.

Second Issue

In a ScriptProperty there is no output pipe (any output is thrown away), so echo (being an alias for Write-Output) won't do anything useful. Replacing it with Write-Host works. In general side effects in a property get or set (including output) are poor practice (there is an expectation of low overhead when using them).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!