In PowerShell (v2), how do you add private members to a PSObject?
That is, members that can only be accessed via $this
from within a ScriptProperty or ScriptMethod.
In PowerShell (v2), how do you add private members to a PSObject?
That is, members that can only be accessed via $this
from within a ScriptProperty or ScriptMethod.
Prior to the introduction of classes in version 5.0, the PowerShell extended type system (ETS) doesn't have the same concept of access modifiers as the underlying type system (.NET/CTS) has.
One way of hinting at "don't use this directly" to users, would be to have a prefix for "internal" properties, like __
(double underscore):
$object = New-Object psobject -Property @{
Public = 4
__private = 9
} |Add-Member -MemberType ScriptProperty -Name Private -Value {
$this.__private
} -SecondValue {
param([int]$newValue)
if(($newValue % 3) -ne 0){
Write-Warning "Only multiples of 3 allowed"
} else {
$this.__private = $newValue
}
} -PassThru