How can I implement a get/set property with PowerShell class? Please have a look on my example below:
Class TestObject
{
[DateTime]$StartTimestamp = (Get-Date)
[DateTime]$EndTimestamp = (Get-Date).AddHours(2)
[TimeSpan] $TotalDuration {
get {
return ($this.EndTimestamp - $this.StartTimestamp)
}
}
hidden [string] $_name = 'Andreas'
[string] $Name {
get {
return $this._name
}
set {
$this._name = $value
}
}
}
New-Object TestObject
You can use Add-Member ScriptProperty
to achieve a kind of getter and setter:
class c {
hidden $_p = $($this | Add-Member ScriptProperty 'p' `
{
# get
"getter $($this._p)"
}`
{
# set
param ( $arg )
$this._p = "setter $arg"
}
)
}
Newing it up invokes the initializer for $_p
which adds scriptproperty p
:
PS C:\> $c = [c]::new()
And using property p
yields the following:
PS C:\>$c.p = 'arg value'
PS C:\>$c.p
getter setter arg value
This technique has some pitfalls which are mostly related to how verbose and error-prone the Add-Member
line is. To avoid those pitfalls, I implemented Accessor
which you can find here.
Using Accessor
instead of Add-Member
does an amount of error-checking and simplifies the original class implementation to this:
class c {
hidden $_p = $(Accessor $this {
get {
"getter $($this._p)"
}
set {
param ( $arg )
$this._p = "setter $arg"
}
})
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With