2015-04-22 33 views
4

有沒有辦法在運行腳本時顯示錯誤描述時僅顯示錯誤消息?如何設置powershell腳本以僅顯示簡短的錯誤描述

我有一個運行的腳本,並在發生錯誤時,我會在不同時期的錯誤信息,例如,如果我不傳遞參數給我寫了一個功能,我會得到:

No Setup Location specified (i.e. \\server\share\folder) 
At \\server\share\folder\script.ps1:9 char:31 
+  [string] $setupHome = $(throw <<<< "No Setup Location specified (i.e. \\server\share\folder)") 
    + CategoryInfo   : OperationStopped: (No Setup Locati...ojects\something):String) [], RuntimeException 
    + FullyQualifiedErrorId : No Setup Location specified (i.e. \\server\share\folder) 

這很好,但我希望能夠設置一個首選項(比如ErrorAction),它只會告訴我錯誤消息,並不是所有額外的粘貼都很好,但混亂我的控制檯。因此,而不是上面的,我想只能看到第一行:

No Setup Location specified (i.e. \\server\share\folder) 

回答

5

您可以設置$ErrorView'CategoryView'得到那麼詳細的錯誤報告:

$ErrorView = 'CategoryView' 
Get-Item foo 

ObjectNotFound: (C:\foo:String) [Get-Item], ItemNotFoundException 

默認爲'NormalView',其提供更詳細的輸出:

$ErrorView = 'NormalView' 

Get-Item foo 

ObjectNotFound: (C:\foo:String) [Get-Item], ItemNotFoundException 
Get-Item : Cannot find path 'C:\foo' because it does not exist. 
At line:8 char:1 
+ Get-Item foo 
+ ~~~~~~~~~~~~ 
    + CategoryInfo   : ObjectNotFound: (C:\foo:String) [Get-Item], ItemNotFoundException 
    + FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetItemCommand 
+2

的第一行即真棒。 – Matt

1

可以使用trap功能,把它放在你的腳本開始的每一個異常發生時做一些動作,像這

trap { 
    Write-Host $Error[0].PSMessageDetails 
    continue; 
} 
1

括在一個try/catch塊中的代碼,而在catch塊打印包含在該$錯誤變量與$error.Exception