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 :
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:
- Powershell: reference an object property in another object property from within the same object?
- Powershell PSObject calculated property based on another property
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