通过


终止错误

本主题讨论用于报告终止错误的方法。 它还讨论了如何从 cmdlet 中调用方法,并讨论调用该方法时 Windows PowerShell 运行时可以返回的异常。

发生终止错误时,cmdlet 应通过调用 System.Management.Automation.Cmdlet.ThrowTerminatingError* 方法报告错误。 此方法允许 cmdlet 发送描述导致终止错误的条件的错误记录。 有关错误记录的详细信息,请参阅 Windows PowerShell 错误记录

调用 System.Management.Automation.Cmdlet.ThrowTerminatingError* 方法时,Windows PowerShell 运行时会永久停止执行管道,并引发 System.Management.Automation.PipelineStoppedException 异常。 任何后续尝试调用 System.Management.Automation.Cmdlet.WriteObjectSystem.Management.Automation.Cmdlet.WriteError,或者其他几个 API 会导致这些调用引发 System.Management.Automation.PipelineStoppedException 异常。

如果管道中的另一个 cmdlet 报告终止错误、用户要求停止管道,或者由于任何原因在完成之前已停止管道,则 System.Management.Automation.PipelineStoppedException 异常也可能发生。 该 cmdlet 不需要捕获 System.Management.Automation.PipelineStoppedException 异常,除非它必须清理打开的资源或其内部状态。

Cmdlet 可以在报告终止错误之前写入任意数量的输出对象或非终止错误。 但是,终止错误永久停止管道,无法报告进一步的输出、终止错误或非终止错误。

Cmdlet 只能从调用 System.Management.Automation.Cmdlet.BeginProcessingSystem.Management.Automation.Cmdlet.ProcessRecordSystem.Management.Automation.Cmdlet.EndProcessing 输入处理方法的线程调用 System.Management.Automation.Cmdlet.ThrowTerminatingError* 。 请勿尝试从另一个线程调用 System.Management.Automation.Cmdlet.ThrowTerminatingError*System.Management.Automation.Cmdlet.WriteError。 相反,必须将错误传达回主线程。

cmdlet 可以在 System.Management.Automation.Cmdlet.BeginProcessingSystem.Management.Automation.Cmdlet.ProcessRecordSystem.Management.Automation.Cmdlet.EndProcessing 方法的实现中引发异常。 从这些方法引发的任何异常(除了一些停止 Windows PowerShell 主机的严重错误条件除外)被解释为终止错误,该错误会停止管道,而不是整个 Windows PowerShell。 (这仅适用于主 cmdlet 线程。cmdlet 生成的线程中未捕获的异常通常会停止 Windows PowerShell 主机。建议使用 System.Management.Automation.Cmdlet.ThrowTerminatingError* 而不是引发异常,因为错误记录提供了有关错误条件的其他信息,这对最终用户很有用。 Cmdlet 应遵循托管代码准则,防止捕获和处理所有异常(catch (Exception e))。 仅将已知和预期类型的异常转换为错误记录。

另请参阅

System.Management.Automation.Cmdlet.BeginProcessing

System.Management.Automation.Cmdlet.EndProcessing

System.Management.Automation.Cmdlet.ProcessRecord

System.Management.Automation.PipelineStoppedException

System.Management.Automation.Cmdlet.ThrowTerminatingError*

System.Management.Automation.Cmdlet.WriteError

Windows PowerShell 错误记录

编写 Windows PowerShell Cmdlet