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

You see both 100 and the value stored in $minValue as the same, Powershell does not. The reason is the value returned by Measure-Object is a System.Double, where 100 is an integer (System.Int32)

$minValue | Get-Member

   TypeName: System.Double

100 | Get-Member
   TypeName: System.Int32

You can cast the result as an int

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

# or 

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

Or you can use the ToInt32 method on the double

$containers.IndexOf($minValue.ToInt32($null))
3 Likes

Ah, thank you so much!! It works now!