2008-12-15 65 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 
相關問題