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

  • Note, the 2 answers below offer what is known as computed properties in C#, meaning that the value of IsLessThanZero can change depending on the value of Number.

    If you don't expect the value of Number to change, then the answers on the following links might suffice:


    Use a ScriptProperty, either via Update-TypeData:

    $updateTypeDataSplat = @{
        TypeName   = 'myType'
        MemberName = 'IsLessThanZero'
        Value      = { $this.Number -lt 0 }
        MemberType = 'ScriptProperty'
    }
    
    Update-TypeData @updateTypeDataSplat
    
    $myObject = [pscustomobject] @{
        Number     = 5
        PSTypeName = 'myType'
    }
    $myObject
    

    Or by adding the ScriptProperty to the psobject itself:

    $myObject = [pscustomobject] @{
        Number = 5
    }
    $myObject.PSObject.Members.Add([psscriptproperty]::new(
            'IsLessThanZero', { $this.Number -lt 0 }))
    $myObject