Search code examples
powershellobjecthashtable

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


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”
}

Solution

  • 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