是否有可能获得$ _的数量。在foreach管道中变量?powershell,foreach,获取行数
例子:
$a = 1..9
$a | foreach {if ($_ -eq 5) { "show the line number of $_"}}
我希望你知道我的意思。
谢谢!
是否有可能获得$ _的数量。在foreach管道中变量?powershell,foreach,获取行数
例子:
$a = 1..9
$a | foreach {if ($_ -eq 5) { "show the line number of $_"}}
我希望你知道我的意思。
谢谢!
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是我需要的! 也许我的英语应该更好地描述我的问题更清楚。 ;-) – Stoffi
如果你试图让脚本文件名和行号,你可以使用$ 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:\用户\鲍勃\桌面\测试名为.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/
你试图让'$ _'值,邻你试图获得'$ _'的数组索引吗?你的示例代码中显示的值很好。 – TheMadTechnician