Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading