Search code examples
powershell

Simple way to find position number in a given object for a value


So I do, as an example:

$OUs = Get-ADOrganizationalUnit <blah>

I want to find the position in the array for "Test" (i.e. I want to do some testing where I can refer to the position in the array that $OU.Name -eq "Test" is in, such as $OUs[6]).

I could do with something like:

$number = 0
foreach ($OU in $OUs)
{
    "$($OU.name) - $number"
    $number += 1
}

Is there a quicker and easier way?


Solution

  • To get just the index of the object with a property name whose value is test you can do this on one line like this:

    $object1 = New-Object psobject -Property @{'Name'='test'}
    $object2 = New-Object psobject -Property @{'Name'='nope'}
    $myArray = @($object1, $object2)
    $testIndex = $myArray.IndexOf(($myArray.Where({$_.name -eq 'test'}))[0])
    

    In the above approach, if there is no object with that value then it will return -1. Also note that if multiple objects meet the criteria, this will only return the index of the first item returned. This is due to taking the item at index 0 from the array returned by the Where method.

    Or this:

        $object1 = New-Object psobject -Property @{'Name'='test'}
        $object2 = New-Object psobject -Property @{'Name'='nope'}
        $myArray = @($object1, $object2)
        #this will just output the index to the terminal
        $myArray.ForEach({
            if($_.name -eq 'test'){
                $myArray.IndexOf($_)
            }
        })
        #you can capture the index instead, like this:
        $testIndex = $myArray.ForEach({
           if($_.name -eq 'test'){
               $myArray.IndexOf($_)
           }
       })
    

    This also yields -1 when there is no match.