2008-12-15 24 views

回答

13

是的,是的。

如果您只想更改文字颜色,则可以使用内置的$host对象。但是,您无法更改错误消息本身 - 这是硬编码。

你可以做的是(a)抑制错误信息,而是(b)捕获错误并显示你自己的错误信息。

完成(a)通过设置$ErrorActionPreference = "SilentlyContinue" - 这不会停止错误,但它会抑制消息。

完成(b)需要更多的工作。默认情况下,大多数PowerShell命令不会产生可捕获的异常。所以你必须学会​​运行命令并添加-EA“Stop”参数,以便在出现错误时生成可捕获的异常。一旦你做到了这一点,你可以通过输入创建的外壳陷阱:

trap { 
# handle the error here 
} 

你可以把这个在您的配置文件脚本而不是每次键入它。在陷阱内部,您可以使用Write-Error cmdlet输出您喜欢的任何错误文本。

可能比你想要做的工作多,但基本上你会怎么做你所问的。

7

这里有一些东西可以让你自定义你的控制台输出。您可以在配置文件中随意设置这些设置,或者使函数/脚本可以根据不同目的进行更改。也许你想要一个“不要错过我”的模式,或者在其他人看来“向我展示一切出错”。你可以做一个函数/脚本来改变它们之间的关系。

## 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调用。第二个将发送错误到指定的变量,而不是默认的$错误。

+0

请注意, $ ReportErrorShow *变量实际上在PowerShell 2.0中没有任何效果。请参阅http://technet.microsoft.com/en-us/library/dd347675.aspx – Timbo 2012-03-09 21:35:22

1

此外,你可以做到这一点写入错误文本的具体线路:

$Host.UI.WriteErrorLine("This is an error") 

(道具克里斯·西尔斯此答案)

1

这可能是也可能不是你想要的是,但还有就是你可以设置一个$ ErrorView选项变量:

$ErrorView = "CategoryView" 

这给出了一个更短的一个行错误信息,例如:

[PS]> get-item D:\blah 
ObjectNotFound: (D:\blah:String) [Get-Item], ItemNotFoundException 
相关问题