Removing an item from a array of objects in Powershell

扶醉桌前 提交于 2019-12-10 16:15:19

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!