Stefan Stoychev
Stefan Stoychev

Reputation: 5022

Filter ArrayList on nested property

I have an PowerShell ArrayList ($displayObjects) which contains:

Name  ID  Tags
----  --  ----
Test1 123 {@{id=4567; name=test1;}}
Test2 345 {@{id=4567; name=test1;}, @{id=6789; name=test2}}
Test3 567 {@{id=4567; name=test1;}, @{id=6789; name=test2}, @{id=7890; name=test3}}

And another:

$filter = @('test1', 'test2')

And waht to filter the $displayObjects (Tags.name) based on the values specified in the $filter array.

So in the case above the result should contain only rows 2 and 3 (from $displayObjects).

I've strted thinking and testing with $displayObjects | Where-Object ... but cant think of a way how to loop in there. Any suggestions?

Upvotes: 0

Views: 1142

Answers (2)

TobyU
TobyU

Reputation: 3918

This should work. It might not be the most efficient way, though.

$displayObjects | Where-Object { 
    $tags = [string]$_.Tags
    $returnObject = $true
    $filter | foreach {
        if($tags -notlike "*$_*"){
            $returnObject = $false
        }
    }
    $returnObject
}

Upvotes: 0

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200483

Something like this might work:

... | Where-Object {
    $a = @($_.Tags.name)
    ($filter | Where-Object {$a -contains $_}).Count -eq $filter.Count
}

There is probably a more efficient way to do this with LINQ (like this?), but I'm not versed enough in that.

Upvotes: 5

Related Questions