Home > Blockchain >  Powershell: reference an object property in another object property from within the same object?
Powershell: reference an object property in another object property from within the same object?

Time:10-06

Evening folks, just a small question, if it a possibility.

I know I can do it by calling it as an empty object then adding properties one by one.

$Obj = New-Object PSObject
$Obj.name = “hello”
$Obj.type = $Obj.name ‘ ’ “world”

Is there a way to do this as one property line?

$Obj = New-Object PSObject -Property @{
Name = “hello”
Type = $Obj.name ‘ ’ “world”
}

CodePudding user response:

This might help you accomplish what you're looking for using a PowerShell class:

  • Definition
class SomeClass {
    [string] $Name
    [string] $Type

    SomeClass() { }
    SomeClass([string] $Name, [string] $Type) {
        # ctor for custom Type
        $this.Name = $Name
        $this.Type = $Type
    }

    static [SomeClass] op_Explicit([string] $Name) {
        # explicit cast using only `Name`
        return [SomeClass]::new($Name, $Name   'World')
    }
}

Now you can instantiate using a custom value for the Type:

PS ..\> [SomeClass]@{ Name = 'hello'; Type = 'myCustomType' }

Name  Type
----  ----
hello myCustomType

Or let the explicit operator handle the predefined value for the Type property based on the Name argument:

PS ..\> [SomeClass] 'hello'

Name  Type
----  ----
hello helloWorld

CodePudding user response:

Santiago Squarzon's helpful answer shows how to solve your problem via defining a class that creates a dedicated .NET type.

However, you can avoid creating a dedicated .NET class using the following workaround, which uses an auxiliary variable and the fact that enclosing a variable assignment in (...) passes an assignment's value through:

$obj = [pscustomobject] @{
  Name = ($name = 'hello')  # assign 'hello' to $name and pass the value through
  Type = $name   'world'    # use the value assigned to $name above
}

Note: This relies on the order of property definitions: derived property values must be placed after the ones in which the aux. variables are defined.

Outputting $obj to the display prints:

Name  Type
----  ----
hello helloworld

See also:

  • GitHub issue #13782, which asks for a built-in mechanism for internally cross-referencing the entries of hashtable, which could equally apply to a custom-object literal.
  • Related