4

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")
            {
            $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.

1
  • Thanks for the options. Sounds like I'm trying to over-optimize that operation by trying to apply database thinking to PowerShell. I will stick with just iterating and call it good. Commented May 10, 2011 at 19:49

3 Answers 3

6

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

2 Comments

OK, well if where-object is just doing a full iteration then I won't bother with using that operator then. Is there a more efficient way than looping?
only if you have a key and use some sort of sorted data structure. A Hash for example or you can use the index.
0

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'}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.