# 此API有Bug,结果值为0,原因未知?
function GetCodeLocation($skipFrames=1){
$st = [System.Diagnostics.StackTrace]::new($skipFrames, $true)
$sf = $st.GetFrame(0)
$rowNo = $sf.GetFileLineNumber()
$colNo = $sf.GetFileColumnNumber()
$file = $sf.GetFileName()
$func = $sf.GetMethod().Name
"在文件{0} 函数{1} 第{2}行,第{3}列的信息:{4}" -f $file, $func, $rowNo, $rowNo, $sf
}
function Test1{
# 获取执行语句的行号、列号
$kipFrames = 1
GetCodeLocation -skipFrames $kipFrames
# 获取执行函数的行号、列号
$kipFrames = 0
GetCodeLocation -skipFrames $kipFrames
}
#Test1
Function Test2(){
'调用函数 Test2() 的位置: 行 {0}, 列 {1}' -f $MyInvocation.ScriptLineNumber, $MyInvocation.OffsetInLine
#"`n`$MyInvocation 所有属性信息如下:"
#$MyInvocation | Get-Member -force
#"`n`$MyInvocation 所有实值信息如下:"
#$MyInvocation | Format-List * -force
#"`n`$MyInvocation 所有实值信息如下:"
#$MyInvocation | Format-List -Property *
#"`n`$MyInvocation 所有实值信息(M字母开头)如下:"
#$MyInvocation | Format-List M*
#"`n`$MyInvocation 所有实值信息如下:"
#$MyInvocation | Select *
#"`n`$MyInvocation 所有实值信息(包括子类、子成员)如下:"
#$MyInvocation | format-custom *
}
Test2
# 捕获异常行号、列号
Function Test3(){
trap{
$info=$_.InvocationInfo
"在第{0}行,第{1}列捕获到异常:{2}" -f $info.ScriptLineNumber, $info.OffsetInLine, $_.Exception.Message
continue
}
Get-Service | foreach {1/0}
}
#Test3
exit
################################################################################################################################
# 当前测试版本 Powershell 5.1
# $PSVersionTable
# PSVersion 5.1.22621.963