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+ 浏览量

开启你的 职业生涯

通过完成课程获得认证

开始学习
广告

© . All rights reserved.