4

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?

DDD
  • 43
  • 4
  • 1
    I actually don't know if it's possible but I wonder why you'd need something like this. You could create a string like this *outside* of the `[PSCustomObject]` anytime?! `¯\_(ツ)_/¯` – Olaf Nov 30 '22 at 21:12
  • It is because that string is different for each object and contain item that are already in the object. – DDD Dec 01 '22 at 12:51

1 Answers1

4

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"
} 
Abraham Zinala
  • 4,267
  • 3
  • 9
  • 24