问题
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
回答1:
If I'm reading the question correctly, this should work:
$a = $a | where {$b -contains $_.Name}
回答2:
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})
来源:https://stackoverflow.com/questions/15794576/removing-an-item-from-a-array-of-objects-in-powershell