0

I have a file in a powershell script containing data, say:

1
2
3

If I get a random item from that list, and I have the full list, how could I get the index of the item (3 = $List[2]; 1 = $List[0]? The list is not actual numbers, but that was an example. I am using Powershell 5.1 and have no urgent need for speed, as the list is small.

  • 2
    In short: Use `$array.IndexOf('foo')` for case-_sensitive_ string or non-string lookups, and `[Array]::FindIndex($array, [Predicate[string]] { 'foo' -eq $args[0] })` for case-_insensitive_ string lookups. See the linked duplicate for details. – mklement0 Nov 15 '21 at 20:33

1 Answers1

4

Use IndexOf

Searches for the specified object and returns the index of its first occurrence in a one-dimensional array or in a range of elements in the array.

$List = 1,2,3,4,5
$Random = $List | Get-Random
$Random 
5

$List.IndexOf($Random)
4

For further explanation check out this link

Avshalom
  • 8,657
  • 1
  • 25
  • 43
  • 1
    Nice, though it's worth mentioning that `.IndexOf()` is invariably case-_sensitive_, which may be unexpected / undesired. – mklement0 Nov 15 '21 at 20:34