Question: 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!

Answer: 
**[Array.IndexOf Method](https://msdn.microsoft.com/en-us/library/system.array.indexof(v=vs.110).aspx)** (`.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> 

```
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/>