cmdlets - VBscript Public Property Set/Get equivalent in PowerShell -
i'm trying add elements powershell variable add-member. have no problem adding static properties noteproperty, , methods scriptmethod, :
$variable = new-object psobject $variable | add-member noteproperty key "value" $variable | add-member scriptmethod dosomething { // code }
now i'm stuck on :
i want add property has getter , setter , bunch of things via code block.
the vbscript equivalent :
class myclass public property item(name) // code return value of item "name" end property public property let item(name,value) // code set value of item "name" value "value" end property end class
note code sections need write more set/get value, they're more complex (set other related variables, access external data, etc...).
i failed find easy in powershell , ended adding instead 2 scriptmethods, getitem , setitem.
what best way implement get/let functionnality in member of psobject in powershell ?
thanks in advance
you should add -membertype scriptproperty
, use -value
, -secondvalue
:
# make object script property myproperty $variable = new-object psobject # “internal” value holder $variable | add-member -membertype noteproperty _myproperty -value 42 # get/set methods $get = { write-host "getting..." $this._myproperty } $set = { write-host "setting..." $this._myproperty = $args[0] } # script property $variable | add-member -membertype scriptproperty myproperty -value $get -secondvalue $set
test:
write-host "original value: $($variable.myproperty)" $variable.myproperty = 123 write-host "after assignment: $($variable.myproperty)"
it prints:
getting... original value: 42 setting... getting... after assignment: 123
unfortunately not know how make “protected/private” internal value holders note property _myproperty
in our example (or whether possible @ all).
update: apparently it’s answer more or less title asks. question in fact parameterized property, not get/set methods implemented via script blocks. attempt use type of property (parameterizedproperty
) add-member
has failed, perhaps not yet supported.
Comments
Post a Comment