powershellpscustomobject

In an PSCustomObject, is it possible to refer an item belonging to it inside itself?


I need to keep inside a PSCustomObject, values at 2 or 3 places and these places are different depending of the object created. The object are hard coded in the script but sometime I need to change the values. But instead of change theses value at 2 or 3 places, is it possible to self refer item instead of edit all the place where the values are?

Here is an example that could explain what I'm trying to do:

$objInfo = [PSCustomObject]@{
        name  = 'TheObjectName'
        color = 'red'
        size  = 'small'
        mystring = "The $($self.name) is $($self.color) and $($self.size)"
    }

Is it possible to refer to itself with something like $self?


Solution

  • Add-Member let's you modify your existing object by adding members to it; as the name indicates lol. With that said, you can use the membertype of ScriptProperty to add a value referencing the same objects property using the keyword $this:

    $objInfo = [PSCustomObject]@{
        name  = 'TheObjectName'
        color = 'red'
        size  = 'small'
    } | 
        Add-Member -MemberType 'ScriptProperty' -Name 'MyString' -Value { 
            "The $($this.name) is $($this.color) and $($this.size)." 
        } -PassThru
    

    This can also be done using a class, but to answer your question I used Add-Member. As an alternative, creating the properties value(s) outside your PSCustomObject and then referencing within should give you the same effect. For example:

    $name  = 'TheObjectName'
    $color = 'red'
    $size  = 'small'
    
    $objInfo = [PSCustomObject]@{
        name  = $name
        color = $color
        size  = $size
        mystring = "The $name is $color and $size"
    }