'powershell, foreach, get the number of line

Is there any possibility to get the number of a $_. Variable in a foreach pipe?

Example:

$a = 1..9
$a | foreach {if ($_ -eq 5) { "show the line number of $_"}}

I hope you know what i mean.

Thanks!



Solution 1:[1]

Array.IndexOf Method (.NET Framework)

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.

Examples:

PS D:\PShell> $a = "aa","bb","cc","dd","ee"

PS D:\PShell> $a.IndexOf('cc')
2

PS D:\PShell> $a=101..109

PS D:\PShell> $a.IndexOf(105)
4

PS D:\PShell> $a |foreach {if ($_ -eq 105) {"$($a.IndexOf($_)) is the line number of $_"}}
4 is the line number of 105

PS D:\PShell> 

Solution 2:[2]

If you are trying to get script file name and line numbers you can use the $MyInvocation variable in a function call to get the line number in the script file where the function was called.

Save the following in a ps1 script file:

function Get-CurrentLineNumber {
  return $MyInvocation.ScriptLineNumber
}

function Get-CurrentFileName {
  return $MyInvocation.ScriptName
}

1..9 | % {
  if ($_ -eq 5) {
    "{0}:{1}  value is {2}" -f (Get-CurrentFileName), (Get-CurrentLineNumber), $_
  }
}

After running the script, you should get something like the following output:

// c:\Users\bob\Desktop\Test.ps1:11 value is 5

Shamelessly borrowed from poshoholic's blog here: https://poshoholic.com/2009/01/19/powershell-quick-tip-how-to-retrieve-the-current-line-number-and-file-name-in-your-powershell-script/

Solution 3:[3]

For the original question as it sounds:

foreach ($x in 1..10) {
  Write-Host "Current item number is $($foreach.current)"
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 JosefZ
Solution 2 Doug Coburn
Solution 3 Aurimas N.