考虑脚本
$someComplexCondition = $false
if ($someComplexCondition)
{
Write-Error -Message "Some complex condition"
}
else
{
Write-Error -Message "Other complex condition"
}
当我运行时,它说
C:\Dev> .\MyScript.ps1
C:\Dev\MyScript.ps1 : Other complex condition
At line:1 char:15
+ .\MyScript.ps1 <<<<
+ CategoryInfo : NotSpecified: (:) [Write-Error], WriteErrorException
+ FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,MyScript.ps1
我注意到写错误始终将自己报告为在行:1 根据堆栈跟踪,它看起来像#1行,因为它是从shell调用的,更有趣的是 char:15 ,因为
".\MyScript.ps1 ".Length -eq 15
如果我们更改文件名,则 char:15 将相应更改。
问题是如何在发生错误时获取实际行。
在我们的案例中,我想获得 line:9
答案 0 :(得分:1)
当Powershell生成实际错误时,您会得到一个ErrorRecord类型的对象:
$error[0] | Get-Member
TypeName: System.Management.Automation.ErrorRecord
当您使用与Write-Error相同的ErrorRecord时,您不会得到一个对象:
$myError = Write-Error -ErrorRecord $Error[0]
PS C:\> $MyError | Get-Member
gm : You must specify an object for the Get-Member cmdlet.
At line:1 char:12
+ $MyError | gm
+ ~~
+ CategoryInfo : CloseError: (:) [Get-Member], InvalidOperationException
+ FullyQualifiedErrorId : NoObjectInGetMember,Microsoft.PowerShell.Commands.GetMemberCommand
现在,我们知道Write-Error不会为我们提供任何我们以后可以重用的内容。
您可以使用“投掷”声明:
$someComplexCondition = $false
if ($someComplexCondition)
{
Throw "Some complex condition"
}
else
{
Throw "Other complex condition"
}
然后,当您运行脚本时,错误会为您提供“Throw”语句开头的行号和字符编号:
C:\Test-Error.ps1
Other complex condition
At C:\Test-Error.ps1:9 char:5
+ Throw "Other complex condition"
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OperationStopped: (Other complex condition:String) [], RuntimeException
+ FullyQualifiedErrorId : Other complex condition
这里是第9行。