Davor Josipovic
Davor Josipovic

Reputation: 5504

PowerShell - jagged array filtering with pipeline in pipeline

I have a jagged array $h that I would like to filter. One way to do this is to use pipelines in pipelines, like in the following example:

$h = ((‘a’,’b’,’a’), (‘c’,’d’), (‘a’, ‘f’)) 
$h | foreach {$_ | Where-Object {$_ -Like 'a'} } | foreach { if ($_.Count -gt 0) {<% DO SOMETHING %> }}

As you can see, I am trying to start a new pipeline in the foreach {} statement, hoping it will not interfere with the outer pipeline, but it does. The output is no longer a jagged array, but simply an one dimensional array consisting of strings: (‘a’,’a’,’a’)

What I wanted to see was ((‘a’,’a’),’a’).

In reality, ‘a’, ‘b’ etc. are custom objects with properties, grouped in arrays in jagged array $h.

What is the most elegant way to solve this?

Upvotes: 2

Views: 259

Answers (1)

Frode F.
Frode F.

Reputation: 54871

Does this solve it for you? I removed [0] as I didn't see a use for it. I also made sure that multiple results are delivered in an outer array using ,):

$h = ((‘a’,’b’,’a’), (‘c’,’d’), (‘a’, ‘f’)) 
$h | foreach { ,($_ | Where-Object {$_ -Like 'a'}) } | foreach { if ($_.Count -gt 0) {<% DO SOMETHING %> }}

Upvotes: 3

Related Questions