【发布时间】:2016-10-30 02:26:38
【问题描述】:
如何从 PowerShell 写入标准错误,或捕获以下错误:
- 错误消息显示为错误(真正写入标准错误以便TeamCity 和 Octopus 将其视为错误)
- 没有堆栈跟踪垃圾会混淆我漂亮、简洁的错误消息
这些年来,我在throwing 错误或通过Write-Error 写作中幸存下来,但我又累又老,在我的脚本中我只想看到一条简洁的错误消息。我一直在尝试trap、throw、Write-Error 和-ErrorAction 的所有组合,但无济于事:
try {
throw "error" # Sample code for a stack overflow. In the theater
# of your mind, imagine there is code here that does something real and useful
} catch {
Write-Error "An error occurred attempting to 'do something.' Have you tried rebooting?"
}
这是我想看到的用户体验:
C:\> & .\Do-Something.ps1
An error occurred attempting to 'do something.' Have you tried rebooting?
C:\> ▏
相反,我得到:
C:\> & .\Do-Something.ps1
An error occurred attempting to 'do something.' Have you tried rebooting?
At line:1 char:1
+ Do-RealWork
+ ~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Write-Error], WriteErrorException
+ FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,Do-RealWork
C:\> ▏
【问题讨论】:
-
FWIW
$error[0].Exception.Message包含错误消息,但我不确定这对您是否有用。
标签: powershell error-handling stderr exit-code