VBscript Public Property Set / Get equivalent in PowerShell

I am trying to add elements to a Powershell variable using Add-Member. I have no problem adding static properties using NoteProperty and methods with ScriptMethod, for example:

$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 getter and setter, and does a bunch of things through a code block.

The equivalent of VBScript will be as follows:

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 sections of code that I need to write are more than just setting / getting the value, they are more complicated than that (setting other related variables, accessing external data, etc.).

I was unable to find anything in PowerShell, and eventually added 2 scriptmethod, GetItem and SetItem methods instead.

get/let PSObject PowerShell?

+3
1

-MemberType ScriptProperty -Value -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

:

Write-Host "Original value: $($variable.MyProperty)"
$variable.MyProperty = 123
Write-Host "After assignment: $($variable.MyProperty)"

:

Getting...
Original value: 42
Setting...
Getting...
After assignment: 123

, , "/" , _MyProperty ( ).

: -, , . , , get/set, script. (ParameterizedProperty) Add-Member , , .

+2

Source: https://habr.com/ru/post/1774945/


All Articles