powershellpsobject

psobject declaration literals - Is there a way for a property value to reference the value of another property within the declaration itself?


Simply put, is there a way to reference (existing) property values inside of a psobject declaration literal, basically like this?

[pscustomobject] @{
    Number = 5
    IsLessThanZero = $this.Number -lt 0
}




Response to comments and answers:


Solution

  • Santiago's helpful answer is focused on a dynamic solution that makes the .IsLessThanZero property dynamically reflect the then-current value of the .Number property.


    By contrast, you seem to be looking for a solution based on [pscustomobject] literals, i.e. to initialize the .IsLessThanZero property statically, based on the initial, literally specified .Number value earlier in the same (pseudo) hashtable (ostensibly) cast to [pscustomobject] (the [pscustomobject] @{ ... } construct is syntactic sugar for constructing [pscustomobject] instances).

    As of PowerShell 7.4.x, there is no syntactic sugar to support such intra-hashtable cross-references.

    For now, you can use the following workaround:

    [pscustomobject] @{
        Number = ($number = 5)
        IsLessThanZero = $number -lt 0
    }
    

    Note: The $number variable will linger in the caller's scope; to avoid that, you can enclose the entire expression in & { ... }, which outputs the constructed object while confining the variable assignments to a transient child scope.