Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter list for objects missing a property

Tags:

powershell

I have a generic list of custom objects that look like this:

id             : 1
displayName    : server1.domain.tdl
autoProperties : { @{name = auto.bios_version; value = 6.00 }, @{name = auto.specialDevice; value = True} }

id             : 2
displayName    : server2.domain.tdl
autoProperties : { @{name = auto.bios_version; value = 6.00 } }

Some of them have the "auto.SpecialDevice" property and some do not. I am trying to filter out those that do NOT have "auto.SpecialDevice".

As a sample, this code gets to what I have:

$string = '    [
        {
            "id":  1,
            "displayName": "server1.domain.tdl",
            "autoProperties":  [
                {
                    "name":  "auto.bios_version",
                    "value":  "6.00"
                },
                {
                    "name":  "auto.specialDevice",
                    "value":  "True"
                }
            ]
        },
        {
            "id":  2,
            "displayName": "server2.domain.tdl",
            "autoProperties":  [
                {
                    "name":  "auto.bios_version",
                    "value":  "6.00"
                }
            ]
        }
    ]
'
$list = [System.Collections.Generic.List[PSObject]]::New()
$list.Add(($string | ConvertFrom-Json))

So, the objects are in a variable called, $list, then I have tried the following, which returns both devices:

$list | Where-Object { -Not $_.autoProperties['auto.specialDevice'] }

What is the right way to do this?

like image 833
StackExchangeGuy Avatar asked Dec 12 '25 14:12

StackExchangeGuy


1 Answers

(adding list population code suggested by @ansgar wiechers and @john rees)

You can populate the list from that json like this:

$list = $string | ConvertFrom-Json

Once you have the list populated with these objects, the following will work:

$list | where {$_.Autoproperties.name -notcontains 'auto.specialDevice'}

That is because $_.AutoProperties.name is a list of all of the names in the autoproperties collection.

like image 113
Mike Shepard Avatar answered Dec 15 '25 19:12

Mike Shepard