I have an array object $a which returns an output like below.
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
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.
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.
If I'm reading the question correctly, this should work:
$a = $a | where {$b -contains $_.Name}
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})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With