5

I have an array object $a which returns an output like below.

Suppose $a returns this

And by doing $a[0].Name I can access each "Name" entry, $a[0].Available I can access its corresponding Available space.

I have another array say $b which contains some names, say $b returns me two names "sandeep_aggr1" and "aggr4". This is just an array (no properties like Name, Avaiable), not an object, so It can't use Compare-Object.

I want to remove other entries in the original object $a, except for those with "Name" equal to "sandeep_aggr1" and "aggr4".

This is what I am doing.

foreach($bb in $b)
    {
          foreach($aa in $a)
          {
                if($aa.Name -ne $bb)
                {
                   $aa.Remove($aa.Name)
                }

          }


    }

    echo $a

But, I don't see the elements deleted, am I missing something here ? Any help appreciated

2 Answers 2

10

If I'm reading the question correctly, this should work:

$a = $a | where {$b -contains $_.Name}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, didn't expect that it's that easy using pipe. Works exactly as expected.
1

I had the same problem and it doesn't work if $a become an array with only one element. Powershell loose the fact that $a is an array. That was very problematic because I used JSON convertion just after.

I just added a cast:

$a = [array]($a | where {$b -contains $_.Name})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.