George
George

Reputation: 11

Use ExpandProperty to select a single property from an object

when I do something like:

Get-Objects | Where ($_.prop1 -ne $null} | select -ExpandProperty prop1

It returns all objects where prop1 aren't null. What if I want to get all objects where subprop = "10" , for example get all objects where prop1.subprop = 10, and select that value?

Do we have something like Get-Objects | where { $_.prop1/subprop -eq "10"} | select -ExpandProperty prop1/subprop?

I am not sure how to make it work like this

Upvotes: 1

Views: 443

Answers (1)

iRon
iRon

Reputation: 23663

First of all, a note from About Comparison Operators:

If you need to compare a value to $null you should put $null on the left-hand side of the comparison. When you compare $null to an Object[] the result is False because the comparison object is an array. When you compare an array to $null, the comparison filters out any $null values stored in the array.

PowerShell has two nice features:

  1. Member enumeration (PowerShell v3+)
  2. The equality operators (-eq, -ne) return a value of TRUE or the matches when one or more of the input values is identical to the specified pattern.

This means if you just looking for the values of the sub-properties, the syntax is as simple as this:

(Get-Objects).prop1.subprop -eq 10

Example:

Function Get-Objects {
    [pscustomobject]@{
        Prop1 = [pscustomobject]@{SubProp1a = 10; SubProp1b = 11}
        Prop2 = [pscustomobject]@{SubProp2a = 20; SubProp2b = 11}
    },
    [pscustomobject]@{
        Prop1 = [pscustomobject]@{SubProp1a = 20; SubProp1b = 22}
        Prop2 = [pscustomobject]@{SubProp2a = 10; SubProp2b = 22}
    },
    [pscustomobject]@{
        Prop1 = [pscustomobject]@{SubProp1a = 10; SubProp1b = 33}
        Prop2 = [pscustomobject]@{SubProp2a = 20; SubProp2b = 33}
    }
}

(Get-Objects).Prop1.SubProp1a -eq 10
10
10
(Get-Objects).Prop1.SubProp1b -gt 20
22
33

Upvotes: 1

Related Questions