I'm trying to add elements to a Powershell variable with Add-Member. I have no 开发者_开发知识库problem adding static properties with NoteProperty, and methods with ScriptMethod, like that :
$variable = New-Object PSObject
$variable | Add-Member NoteProperty Key "Value"
$variable | Add-Member ScriptMethod DoSomething { // code }
Now I'm stuck on this :
I want to add a property that has a getter and a setter and does a bunch of things via code block.
The VBScript equivalent would be this :
Class MyClass
Public Property Get Item(name)
// Code to return the value of Item "name"
End Property
Public Property Let Item(name,value)
// Code to set the value of Item "name" to value "value"
End Property
End Class
Note that the code sections I need to write do more than just set/get the value, they're more complex than that (set other related variables, access external data, etc...).
I failed to find anything this easy in PowerShell and ended up adding instead 2 scriptmethods, GetItem and SetItem.
What would be the best way to implement this get/let functionnality in a member of a PSObject in PowerShell ?
Thanks in advance
You should add -MemberType ScriptProperty
and use -Value
and -SecondValue
:
# Make an object with the 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]
}
# the 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 I do not know how to make “protected/private” internal value holders like the note property _MyProperty
in our example (or whether it is possible at all).
UPDATE: Apparently it’s the answer to what more or less the title asks. But the question is in fact about parameterized property, not just get/set methods implemented via script blocks. My attempt to use this type of property (ParameterizedProperty
) with Add-Member
has failed, perhaps it is not yet supported.
精彩评论