Find the Row Index of a PowerShell Array
Here’s a function that will find the index of a Powershell array row, when the column you specify is also the value you’re searching:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
# Create function to find array row index function Get-ArrayRowIndex{ param( [parameter(mandatory=$true)]$Property, [parameter(mandatory=$true)]$Value ) $index = 0 # Loop through array, incrementing index until value is found. while($index -lt ($arrayName.$Property.count)){ if($arrayName.rows[$index].$Property -eq $Value){break} $index++ } return $index } |
This function is array specific, so in the script, it will only return the index for an array “$ArrayName.” It can be duplicated per array if needed, by replacing the array name appropriately.
Let’s say we have an array with “ID”,”Name”,”Notes” as its columns and want to search by Name and find the row index where the value is “MyName”:
Get-ArrayRowIndex -Property Name -Value "MyName"
This will return the first row that equals “MyName.”
To find a reference for returning a row with WHERE-Object, and updating a specific value in an existing row: View the Update Existing Value In PowerShell Array article.