【发布时间】:2010-09-27 01:35:57
【问题描述】:
我发现标准的 Powershell 错误显示(红色文本、多行显示)有点让人分心。可以自定义吗?
【问题讨论】:
我发现标准的 Powershell 错误显示(红色文本、多行显示)有点让人分心。可以自定义吗?
【问题讨论】:
是的,是的。
如果您只想更改文本颜色,则可以使用内置的$host 对象。但是,您不能更改错误消息本身 - 这是硬编码的。
您可以做的是 (a) 隐藏错误消息,而是 (b) 捕获错误并显示您自己的错误。
通过设置 $ErrorActionPreference = "SilentlyContinue" 来完成 (a) - 这不会停止错误,但会抑制消息。
完成 (b) 需要更多的工作。默认情况下,大多数 PowerShell 命令不会产生可捕获的异常。因此,您必须学习运行命令并添加 -EA "Stop" 参数以在出现问题时生成可捕获的异常。完成后,您可以通过键入以下内容在 shell 中创建一个陷阱:
trap {
# handle the error here
}
您可以将其放入您的个人资料脚本中,而不是每次都输入。在陷阱内,您可以使用 Write-Error cmdlet 输出您喜欢的任何错误文本。
可能比您想做的工作更多,但这基本上就是您按要求做的方式。
【讨论】:
这里有一堆东西可以让你自定义你的控制台输出。您可以在个人资料中随意设置这些设置,或制作函数/脚本来更改它们以用于不同目的。也许你有时想要一个“不要打扰我”模式,或者在其他人那里想要一个“告诉我一切都错了”。您可以制作一个函数/脚本在它们之间进行更改。
## Change colors of regular text
$Host.UI.RawUI.BackGroundColor = "DarkMagenta"
$Host.UI.RawUI.ForeGroundColor = "DarkYellow"
## Change colors of special messages (defaults shown)
$Host.PrivateData.DebugBackgroundColor = "Black"
$Host.PrivateData.DebugForegroundColor = "Yellow"
$Host.PrivateData.ErrorBackgroundColor = "Black"
$Host.PrivateData.ErrorForegroundColor = "Red"
$Host.PrivateData.ProgressBackgroundColor = "DarkCyan"
$Host.PrivateData.ProgressForegroundColor = "Yellow"
$Host.PrivateData.VerboseBackgroundColor = "Black"
$Host.PrivateData.VerboseForegroundColor = "Yellow"
$Host.PrivateData.WarningBackgroundColor = "Black"
$Host.PrivateData.WarningForegroundColor = "Yellow"
## Set the format for displaying Exceptions (default shown)
## Set this to "CategoryView" to get less verbose, more structured output
## http://blogs.msdn.com/powershell/archive/2006/06/21/641010.aspx
$ErrorView = "NormalView"
## NOTE: This section is only for PowerShell 1.0, it is not used in PowerShell 2.0 and later
## More control over display of Exceptions (defaults shown), if you want more output
$ReportErrorShowExceptionClass = 0
$ReportErrorShowInnerException = 0
$ReportErrorShowSource = 1
$ReportErrorShowStackTrace = 0
## Set display of special messages (defaults shown)
## http://blogs.msdn.com/powershell/archive/2006/07/04/Use-of-Preference-Variables-to-control-behavior-of-streams.aspx
## http://blogs.msdn.com/powershell/archive/2006/12/15/confirmpreference.aspx
$ConfirmPreference = "High"
$DebugPreference = "SilentlyContinue"
$ErrorActionPreference = "Continue"
$ProgressPreference = "Continue"
$VerbosePreference = "SilentlyContinue"
$WarningPreference = "Continue"
$WhatIfPreference = 0
您还可以在 cmdlet 上使用 -ErrorAction 和 -ErrorVariable 参数来仅影响该 cmdlet 调用。第二个会将错误发送到指定的变量,而不是默认的 $Error。
【讨论】:
这可能是也可能不是您想要的,但是您可以设置一个 $ErrorView 首选项变量:
$ErrorView = "CategoryView"
这给出了一个较短的单行错误消息,例如:
[PS]> get-item D:\blah
ObjectNotFound: (D:\blah:String) [Get-Item], ItemNotFoundException
【讨论】:
此外,您可以这样做来编写特定的错误文本行:
$Host.UI.WriteErrorLine("This is an error")
(克里斯·西尔斯对此答案的支持)
【讨论】: