Powershell - 如何複製陷阱中的完整錯誤訊息

Powershell - 如何複製陷阱中的完整錯誤訊息

我使用Powershell的trap功能是因為我想在發生錯誤時輸出完整的錯誤訊息並且我必須回覆錯誤。如果不使用陷阱,Powershell 將不會向我顯示錯誤訊息,直到發生錯誤(以及我回應的任何查詢提示)之後。

使用陷阱功能的問題是,雖然我可以使用列印完整訊息,但$error[0]我不知道如何將其複製到字串並獲取完整資訊。相反,我只得到簡短的訊息。

例如,這顯示了完整資訊:

$ErrorActionPreference = "Stop"
trap {$error[0]; Read-Host -Prompt "Trapped. Press Enter to exit"}
Split-Path -BAD
echo "Running script"
Read-Host -Prompt "Press Enter to exit"

Split-Path : A parameter cannot be found that matches parameter name 'BAD'.
At line:3 char:12
+ Split-Path -BAD
+            ~~~~
    + CategoryInfo          : InvalidArgument: (:) [Split-Path], ParameterBindingException
    + FullyQualifiedErrorId : NamedParameterNotFound,Microsoft.PowerShell.Commands.SplitPathCo 
   mmand

Trapped. Press Enter to exit: 

Split-Path : A parameter cannot be found that matches parameter name 'BAD'.
At line:3 char:12
+ Split-Path -BAD
+            ~~~~
    + CategoryInfo          : InvalidArgument: (:) [Split-Path], ParentContainsErrorRecordExce 
   ption
    + FullyQualifiedErrorId : NamedParameterNotFound,Microsoft.PowerShell.Commands.SplitPathCo 
   mmand

但如果我嘗試使用 Write-Host 中的 $error[0] ,它只會顯示簡短的錯誤訊息:

$ErrorActionPreference = "Stop"
trap {Write-Host -ForegroundColor Red -BackgroundColor Black "$($error[0])"; Read-Host -Prompt "Trapped. Press Enter to exit"}
Split-Path -BAD
echo "Running script"
Read-Host -Prompt "Press Enter to exit"

A parameter cannot be found that matches parameter name 'BAD'.
Trapped. Press Enter to exit: 

Split-Path : A parameter cannot be found that matches parameter name 'BAD'.
At line:3 char:12
+ Split-Path -BAD
+            ~~~~
    + CategoryInfo          : InvalidArgument: (:) [Split-Path], ParentContainsErrorRecordExce 
   ption
    + FullyQualifiedErrorId : NamedParameterNotFound,Microsoft.PowerShell.Commands.SplitPathCo 
   mmand

我想用顏色顯示陷阱中的完整錯誤訊息,這就是我需要 Write-Host 的原因。

答案1

當您$Error[0]在字串內部使用時,ToString()會隱式調用,僅傳回錯誤字串。用於Out-String取得完整的錯誤輸出:

trap {
    Write-Host -ForegroundColor Red -BackgroundColor Black "$($Error[0] | Out-String)"
    Read-Host "Press enter"

}

或使用Write-Error

trap {
    Write-Error $Error[0]
    Read-Host "Press enter"

}

相關內容