Home > Software design >  Check if property exist before multiplying it to another property inside an object?
Check if property exist before multiplying it to another property inside an object?

Time:06-16

I have an object and iterating over it and multiplying A, B, C together. B is a list and I'm using the count of elements inside of it. Sometimes, B does not exist.

$sum = ( $arrOfObjects | forEach-Object {$_.A * $_.B.Count * $_.C.Count } | Measure-Object -Sum).Sum

This works as long as A, B, C exist. Now, how do I create a check to make sure B exists before using its count.

If B doesn't exist, I'd like to use 1 as the number.

Thank you.

CodePudding user response:

In PowerShell (Core) 7 , you can use a ternary conditional for a concise solution:

$_.A * ($null -eq $_.B ? 1 : $_.B.Count) * $_.C.Count

In Windows PowerShell, use an if statement enclosed in $(...), the subexpression operator:

$_.A * $(if ($null -eq $_.B) { 1 } else { $_.B.Count }) * $_.C.Count

Note:

  • The solutions above do not distinguish between $_ not having a B property and having such a property but with a value of $null
  • If you need to distinguish these cases, replace $null -eq $_.B with
    $null -eq $_.psobject.Properties['B'], which uses the intrinsic .psobject property for reflection in order to test the presence of a property with the given name.
    • This has the added advantage of not retrieving the value of the property during the test, which - situationally, though not typically - can be more costly than the reflection being performed.
  • Related