【问题标题】:powershell, foreach, get the number of linepowershell,foreach,获取行数
【发布时间】:2017-07-10 23:25:47
【问题描述】:

有没有可能得到一个 $_ 的号码。 foreach 管道中的变量?

例子:

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

我希望你明白我的意思。

谢谢!

【问题讨论】:

  • 您是要获取$_ 的值,还是要获取$_ 的数组索引?您在示例代码中的内容显示了该值就好了。

标签: powershell foreach


【解决方案1】:

Array.IndexOf Method.NET 框架)

搜索指定对象并返回其第一个的索引 出现在一维数组或元素范围内 数组。

示例

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> 

【讨论】:

  • 谢谢,IndexOf 正是我所需要的!也许我的英语应该更好地更清楚地描述我的问题。 ;-)
【解决方案2】:

如果您尝试获取脚本文件名和行号,您可以在函数调用中使用 $MyInvocation 变量来获取调用该函数的脚本文件中的行号。

将以下内容保存在 ps1 脚本文件中:

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), $_
  }
}

运行脚本后,您应该会得到如下输出:

// c:\Users\bob\Desktop\Test.ps1:11 值为 5

这里无耻地借用了 poshoholic 的博客: https://poshoholic.com/2009/01/19/powershell-quick-tip-how-to-retrieve-the-current-line-number-and-file-name-in-your-powershell-script/

【讨论】:

    【解决方案3】:

    对于听起来的原始问题:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-07-27
      • 2021-05-25
      • 2010-09-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多