Question about searching PS Objects

Hi guys. I’m learning the basics of PS Objects. What I’m trying to do is to find a way to search for certain information within a group of nested objects, kind of like a database. So in the below example what command can I type to search for all the nested objects within $juices that have type=‘apple’ ? Is there a cmdlet similar to Get-Childitem for searching objects?

$j1 = [pscustomobject]@{type=‘apple’;volume=‘4’}
$j2 = [pscustomobject]@{type=‘apple’;volume=‘6’}
$j3 = [pscustomobject]@{type=‘apple’;volume=‘4’}
$j4 = [pscustomobject]@{type=‘lemon’;volume=‘4’}
$j5 = [pscustomobject]@{type=‘orange’;volume=‘4’}
$j6 = [pscustomobject]@{type=‘lemon’;volume=‘2’}
$j7 = [pscustomobject]@{type=‘apple’;volume=‘9’}
$j8 = [pscustomobject]@{type=‘orange’;volume=‘5’}

$juices= [pscustomobject]@{juice1=$j1;juice2=$j2;juice3=$j3;juice4=$j4;juice5=$j5;juice6=$j6;juice7=$j7;juice8=$j8}
$farmerjoe= [pscustomobject]@{juices=$juices}

So you’d need to have all your objects in an array to start with. For most things with PS, the method you get your objects with will often give you an array of objects anyway. In this example, you’d just do this:

$Objects = $j1, $j2, $j3, $j4, $j5, $j6, $j7, $j8

Then you can use the Where-Object cmdlet to filter out objects you don’t want.

$Objects | Where-Object Type -eq 'Apple'

The alternate syntax for more complex queries uses a script block:

$Objects | Where-Object {$_.Type -eq 'Apple'}


So is there any other way that doesn’t require me to type all the nested objects ? $j1, $j2, $j3, $j4, $j5, $j6, $j7, $j8

How does a scriptblock work for this?

When I do $Objects | Where-Object {$_.Type -eq ‘Apple’}
nothing happens

You could always construct the array from the get-go and save yourself the hassle of having twelve different variables:

$Objects = @(

Give that a shot with both syntax forms. It may also depend on your version of PowerShell – check $PSVersionTable and see what Version you’re on. :slight_smile: