大多数时候,powershell 中的错误报告非常有用。我看到了错误,看到了起源,但我注意到 ForEach-Object 管道中的任何错误都会丢失其起源行,并且错误堆栈仅指向带有ForEach-Object
.
错误位置示例
Set-StrictMode -Version Latest
$ErrorActionPreference = "Stop"
[cultureinfo]::CurrentUICulture = 'en-US'
function Test-Something($val)
{
# var is not defined here
Write-Host($undefined_variable)
}
@("a","b") | ForEach-Object{
$entry = $_
Test-Something $entry
}
结果是
ForEach-Object : The variable '$undefined_variable' cannot be retrieved because it has not been set.
In D:\dummy.ps1:12 Line:14
+ @("a","b") | ForEach-Object{
+ ~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (undefined_variable:String) [ForEach-Object], RuntimeException
+ FullyQualifiedErrorId : VariableIsUndefined,Microsoft.PowerShell.Commands.ForEachObjectCommand
该线12
指向@("a","b") | ForEach-Object{
,这显然不是错误位置。
foreach 的更有用的示例
现在我使用的是foreach
(只有最后4行代码发生了变化)
Set-StrictMode -Version Latest
$ErrorActionPreference = "Stop"
[cultureinfo]::CurrentUICulture = 'en-US'
function Test-Something($val)
{
# var is not defined here
Write-Host($undefined_variable)
}
$data = @("a","b")
foreach($entry in $data)
{
Test-Something $entry
}
现在的错误更加有用,它实际上指向错误9
行Write-Host($undefined_variable)
The variable '$undefined_variable' cannot be retrieved because it has not been set.
In D:\dummy.ps1:9 Line:16
+ Write-Host($undefined_variable)
+ ~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (undefined_variable:String) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : VariableIsUndefined
这是否与管道运营商的管道性质有关,或者我理解有误。当中间有更多函数时,第一种情况使得错误跟踪变得非常困难。在大多数情况下,我可以切换到foreach
,但我很想了解实际发生的情况。