因此,考虑到有四种*方法来报告错误(不包括$ErrorActionPreference、try/catch和trap块的影响,它们有可能改变另一个源报告错误的方式),PowerShell 错误报告似乎是一个巨大的混乱,分钟和糟糕记录了差异,更糟糕的是,没有关于何时使用不同类型的真正说明。(我意识到这会因情况而异,但“标准”是什么——其他人会期望我做什么?)
但这并不是真正的重点。我决定尽可能使用最简单的选项,因为这是我期望大多数其他人都会使用的选项,所以至少我们会保持一致性 - 但我要么没有正确理解某些内容,要么它已损坏。
根据PowerShell 文档,类Activity的属性ErrorCategoryInfo(在 的CategoryInfo属性中观察到System.Management.Automation.ErrorRecord)应该是“遇到错误的操作的文本描述”。考虑到该值是可设置的,并且(在编译的 cmdlet 的情况下)指示 cmdlet 的名称,除非另有指定,我希望基于脚本的错误报告方法具有相同的功能,但我做错了,或者我我们发现 PowerShell 中存在一个自 PowerShell 1.0 以来就普遍存在的错误。
考虑以下示例:
using namespace System.Management.Automation;
function Invoke-Error1 {
[CmdletBinding()]
param()
process {
$ex = [InvalidOperationException]::new()
$er = [ErrorRecord]::new($ex, 'OperationTest', [ErrorCategory]::InvalidOperation, 'MyErrorTarget')
$er.CategoryInfo.Activity = 'MyActivity'
Write-Error -ErrorRecord $er
}
}
Run Code Online (Sandbox Code Playgroud)
调用此函数将导致以下错误。
invoke-error1 : Operation is not valid due to the current state of the object.
At line:1 char:1
+ …Run Code Online (Sandbox Code Playgroud)