Removing an item from an array of objects in Powershell

I have an array object $ a that returns the output as shown below.

Suppose $ a returns this

And by making $ a [0] .Name, I can access every record of "Name", $ a [0]. Available I can access the appropriate available space.

I have another array: $ b, which contains some names, for example $ b returns me two names "sandeep_aggr1" and "aggr4". It is just an array (no properties like Name, Avaiable), not an object, so it cannot use Compare-Object.

I want to delete other entries in the original $ a object, with the exception of those whose "Name" is equal to "sandeep_aggr1" and "aggr4".

This is what I do.

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

But, I don’t see that the items are deleted, am I missing something? Any help appreciated

+4
source share
2 answers

If I read the question correctly, this should work:

 $a = $a | where {$b -contains $_.Name} 
+7
source

I had the same problem and it does not work if $ a becomes an array with only one element. Powershell has lost the fact that $ a is an array. This was very problematic because I used JSON conversion right away.

I just added the cast:

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

All Articles