Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing an item from a array of objects in Powershell

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

like image 391
Sandeep Avatar asked Apr 03 '13 17:04

Sandeep


People also ask

Can you Remove from an array?

Java arrays do not provide a direct remove method to remove an element. In fact, we have already discussed that arrays in Java are static so the size of the arrays cannot change once they are instantiated. Thus we cannot delete an element and reduce the array size.

What is Remove item in PowerShell?

The Remove-Item cmdlet deletes one or more items. Because it is supported by many providers, it can delete many different types of items, including files, folders, registry keys, variables, aliases, and functions.


2 Answers

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

$a = $a | where {$b -contains $_.Name}
like image 139
mjolinor Avatar answered Oct 02 '22 16:10

mjolinor


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})
like image 30
Saveriu CIANELLI Avatar answered Oct 02 '22 16:10

Saveriu CIANELLI