PowerShell 中 $ErrorView 的作用是什麼?


$Errorview 變數決定了 PowerShell 中錯誤訊息的顯示格式。在 PowerShell 7 之前,主要有兩種檢視,

  • 普通檢視(預設檢視)

  • 類別檢視

使用 PowerShell 7 版本,包含一個新的附加錯誤檢視類別,現在 7 版本有 3 個 $ErrorView 類別。

  • 簡潔檢視(預設)

  • 普通檢視

  • 類別檢視

我們將逐一瞭解每個檢視。

A) 普通檢視

它是 PowerShell 7 版本之前的預設檢視,它會生成詳細的多行錯誤,並且有點嘈雜。它包括異常名稱、類別、錯誤的行號等。

$ErrorView = 'NormalView'
Get-ChildItem C:\NoDirectory

輸出

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

單行和結構化檢視,專為生產環境設計。其格式如下。

B) 類別檢視

{Category}: ({TargetName}:{TargetType}):[{Activity}], {Reason}

例如

$ErrorView = 'CategoryView'
Get-ChildItem C:\NoDirectory

輸出

ObjectNotFound: (C:\NoDirectory:String) [Get-ChildItem], ItemNotFoundException

C) 簡潔檢視

PowerShell 7 版本中的預設檢視。它提供了一個簡潔的錯誤訊息。如果錯誤來自命令列,則為單行錯誤訊息。

例如

$ErrorView = 'ConciseView'
Get-ChildItem C:\NoDirectory

輸出

Get-ChildItem: Cannot find path 'C:\NoDirectory' because it does not exist.

如果錯誤來自指令碼,則為包含錯誤訊息和錯誤行號的多行錯誤訊息。

$ErrorView = 'ConciseView'
PS C:\> C:\Temp\TestPS1.ps1

輸出

Error message in Concise view
Get-ChildItem: C:\Temp\TestPS1.ps1:2
Line |
2 | Get-ChildItem c:
onDirectory | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ | Cannot find path 'C:
onDirectory' because it does not exist.

更新於: 2020-09-19

1K+ 瀏覽量

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告