Set a property for a PowerShell class on Instantiation

Viewed 1966

Is it possible to have the value of a property of a PowerShell class defined on instantiation without using a constructor?

Let's say there's a cmdlet that will return Jon Snow's current status (alive or dead). I want that cmdlet to assign that status to a property in my class.

I can do this using a constructor, but I'd like this to happen regardless of which constructor is used, or even indeed if one is used at all.

function Get-JonsCurrentStatus {
    return "Alive"
}

Class JonSnow {

    [string]
    $Knowledge

    [string]
    $Status

    #Constructor 1
    JonSnow()
    {
        $this.Knowledge = "Nothing"
        $this.Status = Get-JonsCurrentStatus
    }

    #Constructor 2
    JonSnow([int]$Season)
    {
        if ($Season -ge 6) 
        {
            $this.Knowledge = "Still nothing"
            $this.Status = Get-JonsCurrentStatus #I don't want to have to put this in every constructor
        }
    }

}

$js = [JonSnow]::new()
$js
2 Answers

You can initialise class properties on instantiation this way:

$jon = new-object JonSnow -Property @{"Status" = Get-JonsCurrentStatus; "Knowledge" = "Nothing"}
Related