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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With