Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array Row index function

Tags:

powershell

I created a function to find an item in an array so I can update it.

  function Get-ArrayRowIndex {
                param(
                    [parameter(mandatory = $true)][array]$Property,
                    [parameter(mandatory = $true)][string]$Value
                )
           
                #Loop through array,incrementing index until value is found. Jordan wrote this and I refined it.
                [int]$index = 0
                while ($index -lt ($Property.count)) {
                    if ($Property[$index] -eq $Value) {
                        break
                    }
                    $index++
                }
                return [int]$index
            }

The problem is when the object is not found the function returns the total number of items in the array. How can I return an error if not found?

like image 749
dcaz Avatar asked Aug 10 '26 15:08

dcaz


1 Answers

If you want to throw an error in case the value isn't found:

function Get-ArrayRowIndex {
                param(
                    [parameter(mandatory = $true)][array]$Property,
                    [parameter(mandatory = $true)][string]$Value
                )
           
                [int]$index = 0
                while ($index -lt ($Property.count)) {
                    if ($Property[$index] -eq $Value) {
                        # Found -> output the value and return (exit) here.
                        return $index 
                    }
                    $index++
                }
                # Getting here means that the value wasn't found.
                throw "'$Value' not found in the given array."
            }

Note that you could use the [Array]::FindIndex() method instead of looping through the array yourself:

# Returns the index if found; -1 otherwise.
[Array]::FindIndex(
  $Property, 
  [Predicate[object]] { $Value -eq $args[0] }
)

[Array].IndexOf() is another option, but only if case-sensitive string comparison is desired (whereas PowerShell's operators, such as -eq used above, are case-insensitive by default); e.g., ('FOO', 'bar').IndexOf('foo') yields -1 (not found) and ('FOO', 'foo').IndexOf('foo') yields 1

like image 58
mklement0 Avatar answered Aug 13 '26 12:08

mklement0