powershellclassoop

Is it possible to override the Getter/Setter functions in a powershell 5 class?


I recently started creating classes with powershell 5. While I was following this awesome guide https://xainey.github.io/2016/powershell-classes-and-concepts/#methods

I was wondering if it is possible to override the get_x and set_x methods.

Example:

Class Foobar2 {
    [string]$Prop1    
}

$foo = [Foobar2]::new()
$foo | gm



Name        MemberType Definition                    
----        ---------- ----------                    
Equals      Method     bool Equals(System.Object obj)
GetHashCode Method     int GetHashCode()             
GetType     Method     type GetType()                
ToString    Method     string ToString()             
Prop1       Property   string Prop1 {get;set;}  

I would like to do it because I think it would be easier for other to access the properties than using my custom Get and Set methods:

Class Foobar {
    hidden [string]$Prop1

    [string] GetProp1() {
        return $this.Prop1
    }

    [void] SetProp1([String]$Prop1) {
        $this.Prop1 = $Prop1
    }
}

Solution

  • Unfortunately the new Classes feature does not have facilities for getter/setter properties like you know them from C#.

    You can however add a ScriptProperty member to an existing instance, which will exhibit similar behavior as a Property in C#:

    Class FooBar
    {
        hidden [string]$_prop1
    }
    
    $FooBarInstance = [FooBar]::new()
    $FooBarInstance |Add-Member -Name Prop1 -MemberType ScriptProperty -Value {
        # This is the getter
        return $this._prop1
    } -SecondValue {
        param($value)
        # This is the setter
        $this._prop1 = $value
    }
    

    Now you can access $_prop1 through the Prop1 property on the object:

    $FooBarInstance.Prop1
    $FooBarInstance.Prop1 = "New Prop1 value"