Forum Discussion

JulianMilano's avatar
JulianMilano
Copper Contributor
Jan 11, 2024

IndexOf does not return the first value of an array!?

I'm tearing my hair out to find out why my code is not returning the first element of an array and thus created this sample code to test what I was seeing and found that the same thing happens.

In the sample code, the first element in the array has the minimal value of all array elements, so finding the minimal value of the array using Measure-Object should give me index #0 right? Nope, it gives me "-1" aka Not Found. But why??

 

 

# Example array
$containers =@(100, 200, 300, 400, 500)

# Find the minimum value
$minValue = ($containers | Measure-Object -Minimum).Minimum

# Find the index of the minimum value
$minContainerIndex = $containers.IndexOf($minValue)

Write-Host "Minimum Value: $minValue"
Write-Host "Index of Minimum Value: $minContainerIndex"

 


Stepping thru the code I can see:
Execute: $minValue = ($containers | Measure-Object -Minimum).Minimum
Returned value: 100
Logic: As expected.

 

Execute: $minContainerIndex = $containers.IndexOf($minValue)
Returned value: -1
Logic: No, No, NO!

Anyone know what I'm doing wrong?

 

 

$PSVersionTable

 Name Value
 ---- -----
 PSVersion 5.1.14393.6343
 PSEdition Desktop
 PSCompatibleVersions {1.0, 2.0, 3.0, 4.0...}
 BuildVersion 10.0.14393.6343
 CLRVersion 4.0.30319.42000
 WSManStackVersion 3.0
 PSRemotingProtocolVersion 2.3
 SerializationVersion 1.1.0.1

 

  • I figured it out. The variables have different types so IndexOf will never find the value in the array:

    $minValue | Get-Member
       TypeName: System.Double
    
    100 | Get-Member
       TypeName: System.Int32

    The solution is to convert the lookup value from a Double to Integer:

     

    [int]$minValue = ($containers | Measure-Object -Minimum).Minimum
    # or 
    $minValue = ($containers | Measure-Object -Minimum).Minimum -as [int]

     

     Tested and works gr8!

  • JulianMilano's avatar
    JulianMilano
    Copper Contributor

    I figured it out. The variables have different types so IndexOf will never find the value in the array:

    $minValue | Get-Member
       TypeName: System.Double
    
    100 | Get-Member
       TypeName: System.Int32

    The solution is to convert the lookup value from a Double to Integer:

     

    [int]$minValue = ($containers | Measure-Object -Minimum).Minimum
    # or 
    $minValue = ($containers | Measure-Object -Minimum).Minimum -as [int]

     

     Tested and works gr8!

Resources