Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell class implement get set property

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
like image 681
Augustin Ziegler Avatar asked Sep 27 '16 06:09

Augustin Ziegler


1 Answers

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"
        }
    })
}
like image 169
alx9r Avatar answered Oct 09 '22 13:10

alx9r