开发者

How to edit a PowerShell array item returned by a search?

I am trying to change a value of a specific item in a hash table. I can do this by iterating through the entire object, testing every single key for a specific value, then changing it if the condition is met like so:

for ($i=0; $i -le $haystack.length-1; $i++)
    {
        if ($haystack[$i].name -eq "needle")
开发者_C百科            {
            $haystack[$i].currentstatus = "found"
            }
    }

The above code works but it seems like there has to be a more efficient way to accomplish the task especially when the haystack is large and there is only one needle.

I tried to use where-object and can find the record I'm looking for:

$haystack | where-object {$_.name -eq "needle"}

This seems much better than doing a brute force search but I do not know how to get at that record now. If I had the index in the array then I can easily use that to edit the value I want so is there a way to get the array index? How is this usually done? Thanks.


If you control the creation of $haystack, and $haystackitem.name is always unique, I would suggest creating a hashtable with Name as the index.

If either of the above conditions are not true, you could speed things up a bit by use foreach ($object in $collection) {} instead. You don't need the index to the object because the objects will be passed by reference. Any changes you make to the object will be seen within the array.

But the best performance would be to create some managed code to sort the array and use an effective search algorithm. But that would be more work.


Where object does a for each any way and has to since it returns all items that match your test condition. The generic use case for a hash is to have a key which you can use to effectively find your object if you are having to iterate perhaps you have chosen a poor key.


You can iterate through the array and retrieve the index for a particular 'name' property value in the array by doing something similar the following:

$index = 0..($haystack.Count - 1) | Where {$haystack[$_].name -eq 'needle'}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜