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

I am trying to change the value of a specific item in a hash table. I can do this, iterate over the entire object, test each individual key for a specific value, and then change it if the condition is true like this:

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

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

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

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

It seems a lot better than brute force, but I don’t know how to get to this record. If I had an index in the array, then I could easily use this to edit the value I want, and is there any way to get the index of the array? How is this usually done? Thanks.

+4
source share
3 answers

If you control the creation of $haystack and $haystackitem.name always unique, I would suggest creating a hash table with the name as an index.

If one of the above conditions is incorrect, you can speed things up a bit using foreach ($object in $collection) {} . You do not need an index for the object, because the objects will be passed by reference. Any changes you make to the object will be visible inside the array.

But the best thing would be to create some managed code to sort the array and use an efficient search algorithm. But it will be more work.

+6
source

Where the object does for everyone in any case and should, since it returns all the elements that match your test condition. A common use case for a hash is to have a key that you can use to efficiently find your object, if you need to iterate, you might have chosen a bad key.

0
source

You can iterate over the array and get the index for the value of the "name" property in the array by doing the following:

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

All Articles